From 4bdfd73347aa0f7101d0fc1acecef2d72cae1cdc Mon Sep 17 00:00:00 2001 From: chen0088 Date: Thu, 1 Aug 2024 21:08:35 +0800 Subject: [PATCH 01/53] add ut Signed-off-by: chen0088 --- tests/unittests/backup_utils/BUILD.gn | 1 + .../b_jsonutil/b_jsonutil_test.cpp | 241 +++++++++++++++--- 2 files changed, 206 insertions(+), 36 deletions(-) diff --git a/tests/unittests/backup_utils/BUILD.gn b/tests/unittests/backup_utils/BUILD.gn index 40476eb1b..e731c8a97 100644 --- a/tests/unittests/backup_utils/BUILD.gn +++ b/tests/unittests/backup_utils/BUILD.gn @@ -293,6 +293,7 @@ group("backup_test") { ":b_file_test", ":b_json_other_test", ":b_json_test", + ":b_jsonutil_test", ":b_process_test", ":b_tarball_cmdline_test", ":b_tarball_factory_test", diff --git a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp index e21b944df..4cb7c1f98 100644 --- a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp +++ b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp @@ -62,6 +62,30 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_ParseBundleNameIndexStr_0100, testing::ext::T GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetDirFiles_0100"; } +/** + * @tc.number: b_jsonutil_ParseBundleNameIndexStr_0200 + * @tc.name: b_jsonutil_ParseBundleNameIndexStr_0200 + * @tc.desc: Test function of ParseBundleNameIndexStr interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_ParseBundleNameIndexStr_0200, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin ParseBundleNameIndexStr_0200"; + try { + std::string bundleName = "com.hos.app01"; + std::string pattern = ":"; + BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName, pattern); + EXPECT_EQ("com.hos.app01", detailInfo.bundleName); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BDirTest-end ParseBundleNameIndexStr_0200"; +} + /** * @tc.number: b_jsonutil_BuildBundleInfos_0100 * @tc.name: b_jsonutil_BuildBundleInfos_0100 @@ -77,63 +101,208 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0100, testing::ext::TestSize try { std::vector bundleNames; std::string bundleName = "com.hos.app01:1"; - std::string bundleName1 = "com.hos.app02"; bundleNames.push_back(bundleName); - bundleNames.push_back(bundleName1); - std::string pattern = ":"; - std::vector detailInfos; - std::string detail01 = "{ - "infos" : [ { - "details" : [ { - "detail" : [ { "source" : "com.ohos.app01", "target" : "com.hos.app01" } ], - "type" : "app_mapping_relation" } ], - "type" : "broadcast" } ] - }"; - detailInfos.push_back(detail01); - detailInfos.push_back(""); + std::vector bundleInfos; + std::string bundleInfo = "info1"; + std::string bundleInfo2 = "info2"; + bundleInfos.push_back(bundleInfo); + bundleInfos.push_back(bundleInfo2); int32_t userId = 100; - std::vector realBundleNames; - std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, userId); - std::string key = "com.hos.app01"; - EXPECT_EQ("com.hos.app01", bundleNameDetailMap[key].bundleName[0]); + std::vector bundleNamesOnly; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_TRUE(result.empty()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; } - GTEST_LOG_(INFO) << "BJsonUtilTest-end b_dir_BuildBundleInfos_0100"; + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0100"; } -/* * - * @tc.number: b_jsonutil_BuildBundleInfos_0101 - * @tc.name: b_jsonutil_BuildBundleInfos_0101 - * @tc.desc: Test function of BuildBundleInfos for enmpty. +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0200 + * @tc.name: b_jsonutil_BuildBundleInfos_0200 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 0 * @tc.require: I6F3GV */ -HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0101, testing::ext::TestSize.Level0) +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0200, testing::ext::TestSize.Level0) { - GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0101"; + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0200"; try { std::vector bundleNames; - std::string bundleName = "com.hos.app01:1"; - std::string bundleName1 = "com.hos.app02"; + std::string bundleName = "bundle"; bundleNames.push_back(bundleName); - bundleNames.push_back(bundleName1); - std::string pattern = ":"; - std::vector detailInfos; - detailInfos.push_back(""); + std::vector bundleInfos; + std::string bundleInfo = "info1"; + bundleInfos.push_back(bundleInfo); int32_t userId = 100; - std::vector realBundleNames; - std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, userId); - EXPECT_EQ(0, bundleNameDetailMap.size()); + std::vector bundleNamesOnly; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0200"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0300 + * @tc.name: b_jsonutil_BuildBundleInfos_0300 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0300, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0300"; + try { + std::vector bundleNames; + std::string bundleName = "bundle1"; + std::string bundleName2 = "bundle2"; + std::string bundleName3 = "bundle3"; + bundleNames.push_back(bundleName); + bundleNames.push_back(bundleName2); + bundleNames.push_back(bundleName3); + std::vector bundleInfos; + std::string bundleInfo = "info1"; + std::string bundleInfo2 = "info2"; + std::string bundleInfo3 = "info3"; + bundleInfos.push_back(bundleInfo); + bundleInfos.push_back(bundleInfo2); + bundleInfos.push_back(bundleInfo3); + int32_t userId = 100; + std::vector bundleNamesOnly; + int32_t size = 3; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_EQ(bundleNamesOnly.size(), size); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0300"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0400 + * @tc.name: b_jsonutil_BuildBundleInfos_0400 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0400, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0400"; + try { + std::vector bundleNames; + std::string bundleName = "bundle1"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":\"type1\",\"details\":\"details1\"}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = 100; + std::vector bundleNamesOnly; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0400"; +} + +/** + * @tc.number: b_jsonutil_FindBundleInfoByName_0100 + * @tc.name: b_jsonutil_FindBundleInfoByName_0100 + * @tc.desc: Test function of FindBundleInfoByName interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_FindBundleInfoByName_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin FindBundleInfoByName_0100"; + try { + std::map> bundleNameDetailsMap; + std::string bundleName = "bundle1"; + std::string jobType = "type"; + BJsonUtil::BundleDetailInfo bundleDetail; + + bool result = BJsonUtil::FindBundleInfoByName(bundleNameDetailsMap, bundleName, jobType, bundleDetail); + EXPECT_EQ(false, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end FindBundleInfoByName_0100"; +} + +/** + * @tc.number: b_jsonutil_FindBundleInfoByName_0200 + * @tc.name: b_jsonutil_FindBundleInfoByName_0200 + * @tc.desc: Test function of FindBundleInfoByName interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_FindBundleInfoByName_0200, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin FindBundleInfoByName_0200"; + try { + std::map> bundleNameDetailsMap; + std::string bundleName = "bundle1"; + std::string jobType = "type"; + BJsonUtil::BundleDetailInfo detailInfo; + detailInfo.bundleName = bundleName; + detailInfo.type = jobType; + bundleNameDetailsMap[bundleName] = {detailInfo}; + BJsonUtil::BundleDetailInfo bundleDetail; + + bool result = BJsonUtil::FindBundleInfoByName(bundleNameDetailsMap, bundleName, jobType, bundleDetail); + EXPECT_EQ(true, result); + EXPECT_EQ(bundleDetail.type, detailInfo.type); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end FindBundleInfoByName_0200"; +} + +/** + * @tc.number: b_jsonutil_BuildRestoreErrInfo_0100 + * @tc.name: b_jsonutil_BuildRestoreErrInfo_0100 + * @tc.desc: Test function of BuildRestoreErrInfo interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildRestoreErrInfo_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildRestoreErrInfo_0100"; + try { + std::string jsonStr; + int errCode = 1; + std::string errMsg = "error"; + + bool result = BJsonUtil::BuildRestoreErrInfo(jsonStr, errCode, errMsg); + EXPECT_EQ(true, result); + EXPECT_NE(jsonStr.find("errorCode"), std::string::npos); + EXPECT_NE(jsonStr.find("errorInfo"), std::string::npos); + EXPECT_NE(jsonStr.find("type"), std::string::npos); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; } - GTEST_LOG_(INFO) << "BJsonUtilTest-end b_jsonutil_BuildBundleInfos_0101"; + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildRestoreErrInfo_0100"; } } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From 78b307475098c9bce32be015bdb16531bdf94df4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=99=9F=E9=92=B0?= Date: Fri, 2 Aug 2024 11:16:18 +0800 Subject: [PATCH 02/53] =?UTF-8?q?=E8=A7=A3=E5=86=B3fuzz=E7=9A=84asan?= =?UTF-8?q?=E6=8F=92=E6=A1=A9=E7=BC=96=E8=AF=91=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张晟钰 --- tests/unittests/backup_ext/BUILD.gn | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index d1b805a5d..53f8c95d7 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -324,12 +324,13 @@ ohos_unittest("ext_backup_js_test") { group("backup_ext_test") { testonly = true - - deps = [ - ":ext_backup_js_test", - ":ext_extension_stub_test", - ":ext_extension_test", - ":tar_file_test", - ":untar_file_test", - ] + if (!use_libfuzzer) { + deps = [ + ":ext_backup_js_test", + ":ext_extension_stub_test", + ":ext_extension_test", + ":tar_file_test", + ":untar_file_test", + ] + } } -- Gitee From c33c33249938cdcb4b3eba43b7436a7bd3cb4c44 Mon Sep 17 00:00:00 2001 From: wangpggg Date: Fri, 2 Aug 2024 17:18:47 +0800 Subject: [PATCH 03/53] add ut to cover branches Signed-off-by: wangpeng --- interfaces/common/src/json_utils.cpp | 2 +- tests/mock/napi/include/napi_mock.h | 2 + tests/mock/napi/src/napi_mock.cpp | 11 +- .../backup_ext/ext_backup_js_test.cpp | 463 +++++++++++++++++- 4 files changed, 465 insertions(+), 13 deletions(-) diff --git a/interfaces/common/src/json_utils.cpp b/interfaces/common/src/json_utils.cpp index 30523ac77..3a401b5bb 100644 --- a/interfaces/common/src/json_utils.cpp +++ b/interfaces/common/src/json_utils.cpp @@ -39,7 +39,7 @@ int32_t JsonUtils::GetJsonObjFromPath(nlohmann::json& jsonObj, const std::string jsonFileStream.close(); jsonObj = nlohmann::json::parse(buf.str(), nullptr, false); - if (!jsonObj.is_discarded()) { + if (jsonObj.is_discarded()) { LOGE("Parse json file path %{public}s failed", jsonPath.c_str()); } return 0; diff --git a/tests/mock/napi/include/napi_mock.h b/tests/mock/napi/include/napi_mock.h index bc699b791..5f70f4f02 100644 --- a/tests/mock/napi/include/napi_mock.h +++ b/tests/mock/napi/include/napi_mock.h @@ -60,6 +60,7 @@ public: virtual napi_status napi_create_function(napi_env, const char*, size_t, napi_callback, void*, napi_value*) = 0; virtual napi_status napi_open_handle_scope(napi_env, napi_handle_scope*) = 0; virtual napi_status napi_close_handle_scope(napi_env, napi_handle_scope) = 0; + virtual napi_status napi_is_exception_pending(napi_env, bool*) = 0; public: static inline std::shared_ptr napi = nullptr; }; @@ -96,6 +97,7 @@ public: MOCK_METHOD6(napi_create_function, napi_status(napi_env, const char*, size_t, napi_callback, void*, napi_value*)); MOCK_METHOD2(napi_open_handle_scope, napi_status(napi_env, napi_handle_scope*)); MOCK_METHOD2(napi_close_handle_scope, napi_status(napi_env, napi_handle_scope)); + MOCK_METHOD2(napi_is_exception_pending, napi_status(napi_env, bool*)); }; } // namespace OHOS::FileManagement::Backup #endif // TEST_UNITTEST_MOCK_NAPI_H \ No newline at end of file diff --git a/tests/mock/napi/src/napi_mock.cpp b/tests/mock/napi/src/napi_mock.cpp index 0310429d3..5b672ce66 100644 --- a/tests/mock/napi/src/napi_mock.cpp +++ b/tests/mock/napi/src/napi_mock.cpp @@ -18,12 +18,6 @@ int uv_queue_work(uv_loop_t* loop, uv_work_t* req, uv_work_cb work_cb, uv_after_work_cb after_work_cb) { - if (work_cb) { - work_cb(req); - } - if (after_work_cb) { - after_work_cb(req, 0); - } return OHOS::FileManagement::Backup::Napi::napi->uv_queue_work(loop, req, work_cb, after_work_cb); } @@ -163,4 +157,9 @@ NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) { return OHOS::FileManagement::Backup::Napi::napi->napi_close_handle_scope(env, scope); +} + +napi_status napi_is_exception_pending(napi_env env, bool* result) +{ + return OHOS::FileManagement::Backup::Napi::napi->napi_is_exception_pending(env, result); } \ No newline at end of file diff --git a/tests/unittests/backup_ext/ext_backup_js_test.cpp b/tests/unittests/backup_ext/ext_backup_js_test.cpp index 4e23ad233..b4dce1570 100644 --- a/tests/unittests/backup_ext/ext_backup_js_test.cpp +++ b/tests/unittests/backup_ext/ext_backup_js_test.cpp @@ -38,6 +38,7 @@ namespace OHOS::FileManagement::Backup { using namespace std; using namespace testing; +const int ARG_INDEX_FIRST = 1; const int ARG_INDEX_SECOND = 2; const int ARG_INDEX_FOURTH = 4; const int ARG_INDEX_FIFTH = 5; @@ -782,11 +783,18 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_ExportJsContext_0100, testing::ext:: extBackupJs->ExportJsContext(); EXPECT_TRUE(extBackupJs->jsObj_ == nullptr); + extBackupJs->jsObj_ = make_unique(); + auto refMock = static_cast(extBackupJs->jsObj_.get()); EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); - extBackupJs->jsObj_ = unique_ptr(); + EXPECT_CALL(*refMock, GetNapiValue()).WillOnce(Return(nullptr)); extBackupJs->ExportJsContext(); - EXPECT_TRUE(true); - extBackupJs->jsObj_ = nullptr; + EXPECT_TRUE(extBackupJs->jsObj_ != nullptr); + + int value = 0; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*refMock, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + extBackupJs->ExportJsContext(); + EXPECT_TRUE(extBackupJs->jsObj_ != nullptr); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by ExportJsContext."; @@ -812,16 +820,18 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsMethod_0100, testing::ext::Tes auto ret = extBackupJs->CallJsMethod("", *jsRuntime, nullptr, nullptr, nullptr); EXPECT_EQ(ret, EINVAL); - EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(Return(1)); - EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); ret = extBackupJs->CallJsMethod("", *jsRuntime, nullptr, nullptr, nullptr); EXPECT_EQ(ret, EINVAL); EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); - EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(Return(0)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(DoAll(WithArgs<1, 3>(Invoke( + [](uv_work_t* req, uv_after_work_cb after_work_cb) { + after_work_cb(req, 0); + })), Return(0))); EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); ret = extBackupJs->CallJsMethod("", *jsRuntime, nullptr, nullptr, nullptr); EXPECT_EQ(ret, ERR_OK); @@ -831,4 +841,445 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsMethod_0100, testing::ext::Tes } GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsMethod_0100"; } + +/** + * @tc.number: SUB_backup_ext_js_DoCallJsMethod_0100 + * @tc.name: SUB_backup_ext_js_DoCallJsMethod_0100 + * @tc.desc: 测试 DoCallJsMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DoCallJsMethod_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_DoCallJsMethod_0100"; + try { + string funcName = ""; + InputArgsParser argParserIn = {}; + ResultValueParser retParserIn = {}; + auto param = make_shared(funcName, nullptr, nullptr, argParserIn, retParserIn); + auto ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + param->jsRuntime = jsRuntime.get(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + int scope = 0; + param->argParser = [](napi_env, std::vector &){ return false; }; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + auto ref = make_shared(); + param->argParser = [](napi_env, std::vector &){ return true; }; + param->jsObj = ref.get(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by DoCallJsMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_DoCallJsMethod_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_DoCallJsMethod_0200 + * @tc.name: SUB_backup_ext_js_DoCallJsMethod_0200 + * @tc.desc: 测试 DoCallJsMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DoCallJsMethod_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_DoCallJsMethod_0200"; + try { + string funcName = ""; + InputArgsParser argParserIn = {}; + ResultValueParser retParserIn = {}; + auto param = make_shared(funcName, nullptr, nullptr, argParserIn, retParserIn); + auto ref = make_shared(); + param->argParser = nullptr; + param->retParser = nullptr; + param->jsObj = ref.get(); + + int scope = 0; + napi_value value = nullptr; + param->jsRuntime = jsRuntime.get(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + auto ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + param->retParser = [](napi_env, napi_value){ return false; }; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_call_function(_, _, _, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_escape_handle(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by DoCallJsMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_DoCallJsMethod_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_DoCallJsMethod_0300 + * @tc.name: SUB_backup_ext_js_DoCallJsMethod_0300 + * @tc.desc: 测试 DoCallJsMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DoCallJsMethod_0300, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_DoCallJsMethod_0300"; + try { + string funcName = ""; + InputArgsParser argParserIn = {}; + ResultValueParser retParserIn = {}; + auto param = make_shared(funcName, nullptr, nullptr, argParserIn, retParserIn); + auto ref = make_shared(); + param->argParser = nullptr; + param->retParser = nullptr; + param->jsObj = ref.get(); + + int scope = 0; + napi_value value = nullptr; + param->jsRuntime = jsRuntime.get(); + param->retParser = [](napi_env, napi_value){ return true; }; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_call_function(_, _, _, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_escape_handle(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + auto ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, ERR_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by DoCallJsMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_DoCallJsMethod_0300"; +} + +/** + * @tc.number: SUB_backup_ext_js_InvokeAppExtMethod_0100 + * @tc.name: SUB_backup_ext_js_InvokeAppExtMethod_0100 + * @tc.desc: 测试 InvokeAppExtMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_InvokeAppExtMethod_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_InvokeAppExtMethod_0100"; + try { + ErrCode errCode = BError(BError::Codes::OK); + string result = ""; + auto ret = extBackupJs->InvokeAppExtMethod(errCode, result); + EXPECT_EQ(ret, ERR_OK); + + result = "test"; + ret = extBackupJs->InvokeAppExtMethod(errCode, result); + EXPECT_EQ(ret, ERR_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by InvokeAppExtMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_InvokeAppExtMethod_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackupEx_0100 + * @tc.name: SUB_backup_ext_js_CallJsOnBackupEx_0100 + * @tc.desc: 测试 CallJsOnBackupEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackupEx_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackupEx_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackupEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackupEx_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackupEx_0200 + * @tc.name: SUB_backup_ext_js_CallJsOnBackupEx_0200 + * @tc.desc: 测试 CallJsOnBackupEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackupEx_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackupEx_0200"; + try { + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackupEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackupEx_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackup_0100 + * @tc.name: SUB_backup_ext_js_CallJsOnBackup_0100 + * @tc.desc: 测试 CallJsOnBackup 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackup_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackup_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackup."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackup_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackup_0200 + * @tc.name: SUB_backup_ext_js_CallJsOnBackup_0200 + * @tc.desc: 测试 CallJsOnBackup 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackup_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackup_0200"; + try { + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackup."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackup_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestoreEx_0100 + * @tc.name: SUB_backup_ext_js_CallJSRestoreEx_0100 + * @tc.desc: 测试 CallJSRestoreEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestoreEx_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestoreEx_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestoreEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestoreEx_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestoreEx_0200 + * @tc.name: SUB_backup_ext_js_CallJSRestoreEx_0200 + * @tc.desc: 测试 CallJSRestoreEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestoreEx_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestoreEx_0200"; + try { + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestoreEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestoreEx_0200"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From 4ddb82a1c0e6272e86ef79aa52d8df9d41a20981 Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Fri, 2 Aug 2024 19:15:52 +0800 Subject: [PATCH 04/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: I4e9b66984a8cdb61d386e86ba367ebcda6ba283a --- test/unittest/file_permission_native/BUILD.gn | 2 +- .../src/file_permission_test.cpp | 114 ++++++++++++++++++ 2 files changed, 115 insertions(+), 1 deletion(-) diff --git a/test/unittest/file_permission_native/BUILD.gn b/test/unittest/file_permission_native/BUILD.gn index 96a4bbf5b..bb3fff721 100644 --- a/test/unittest/file_permission_native/BUILD.gn +++ b/test/unittest/file_permission_native/BUILD.gn @@ -50,7 +50,7 @@ ohos_unittest("file_permission_test") { "ipc:ipc_core", "samgr:samgr_proxy", ] - defines = [] + defines = [ "private = public" ] if (sandbox_manarer) { external_deps += [ "sandbox_manager:libsandbox_manager_sdk" ] defines += [ "SANDBOX_MANAGER" ] diff --git a/test/unittest/file_permission_native/src/file_permission_test.cpp b/test/unittest/file_permission_native/src/file_permission_test.cpp index ee998d1d1..f6172e4c3 100644 --- a/test/unittest/file_permission_native/src/file_permission_test.cpp +++ b/test/unittest/file_permission_native/src/file_permission_test.cpp @@ -600,6 +600,120 @@ HWTEST_F(FilePermissionTest, CheckPersistentPermission_test_0003, testing::ext:: }; GTEST_LOG_(INFO) << "FileShareTest-end CheckPersistentPermission_test_0003"; } + +/** + * @tc.name: GetPathPolicyInfoFromUriPolicyInfo_test_0001 + * @tc.desc: Test function of GetPathPolicyInfoFromUriPolicyInfo() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(FilePermissionTest, GetPathPolicyInfoFromUriPolicyInfo_test_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FileShareTest-begin GetPathPolicyInfoFromUriPolicyInfo_test_0001"; + UriPolicyInfo infoA = {.uri = "file://" + BUNDLE_NAME_A + "/storage/001.txt"}; + UriPolicyInfo infoB = {.uri = BUNDLE_NAME_A + "/storage/001.txt"}; + UriPolicyInfo infoC = {.uri = "file://media/Photo/10/1.jpeg"}; + UriPolicyInfo infoD = {.uri = "file://" + BUNDLE_NAME_A + "/storage/001.txt?networkid=5454541547878787878748748"}; + UriPolicyInfo infoE = {.uri = "file://" + BUNDLE_NAME_A + "/storage"}; + std::vector uriPolicies; + uriPolicies.emplace_back(infoA); + uriPolicies.emplace_back(infoB); + uriPolicies.emplace_back(infoC); + uriPolicies.emplace_back(infoD); + uriPolicies.emplace_back(infoE); + vector errorResult; + auto pathPolicies = FilePermission::GetPathPolicyInfoFromUriPolicyInfo(uriPolicies, errorResult); + EXPECT_EQ(pathPolicies.size(), 1); + EXPECT_EQ(pathPolicies[0].path, "/storage"); + ASSERT_TRUE(errorResult.size() == 5); + EXPECT_EQ(errorResult[4], true); + GTEST_LOG_(INFO) << "FileShareTest-end GetPathPolicyInfoFromUriPolicyInfo_test_0001"; +} + +/** + * @tc.name: ParseErrorResults_test_0001 + * @tc.desc: Test function of ParseErrorResults() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(FilePermissionTest, ParseErrorResults_test_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FileShareTest-begin ParseErrorResults_test_0001"; + vector resultCodes; + vector errorResults; + FilePermission::ParseErrorResults(resultCodes, errorResults); + EXPECT_EQ(errorResults.size(), 0); + + resultCodes.push_back(false); + FilePermission::ParseErrorResults(resultCodes, errorResults); + EXPECT_EQ(errorResults.size(), 0); + + resultCodes.push_back(false); + errorResults.push_back(true); + FilePermission::ParseErrorResults(resultCodes, errorResults); + ASSERT_TRUE(errorResults.size() == 1); + EXPECT_EQ(errorResults[0], false); + + errorResults.push_back(true); + errorResults.push_back(true); + FilePermission::ParseErrorResults(resultCodes, errorResults); + ASSERT_TRUE(errorResults.size() == 3); + EXPECT_EQ(errorResults[0], false); + EXPECT_EQ(errorResults[1], false); + EXPECT_EQ(errorResults[2], false); + GTEST_LOG_(INFO) << "FileShareTest-end ParseErrorResults_test_0001"; +} + +/** + * @tc.name: ParseErrorResults_test_002 + * @tc.desc: Test function of ParseErrorResults() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(FilePermissionTest, ParseErrorResults_test_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FileShareTest-begin ParseErrorResults_test_002"; + PolicyInfo infoA = {.path = "file://" + BUNDLE_NAME_A + "/storage/001.txt"}; + PolicyInfo infoB = {.path = BUNDLE_NAME_A + "/storage/001.txt"}; + PolicyInfo infoC = {.path = "file://media/Photo/10/1.jpeg"}; + PolicyInfo infoD = {.path = "file://" + BUNDLE_NAME_A + "/storage/001.txt?networkid=5454541547878787878748748"}; + PolicyInfo infoE = {.path = "file://" + BUNDLE_NAME_A + "/storage"}; + std::vector uriPolicies; + uriPolicies.emplace_back(infoA); + uriPolicies.emplace_back(infoB); + uriPolicies.emplace_back(infoC); + uriPolicies.emplace_back(infoD); + uriPolicies.emplace_back(infoE); + vector resultCodes; + resultCodes.emplace_back(static_cast(PolicyErrorCode::PERSISTENCE_FORBIDDEN)); + resultCodes.emplace_back(static_cast(PolicyErrorCode::INVALID_MODE)); + resultCodes.emplace_back(static_cast(PolicyErrorCode::INVALID_PATH)); + resultCodes.emplace_back(static_cast(PolicyErrorCode::PERMISSION_NOT_PERSISTED)); + + deque errorResults; + FilePermission::ParseErrorResults(resultCodes, uriPolicies, errorResults); + ASSERT_TRUE(errorResults.size() == 0); + + resultCodes.emplace_back(5); + FilePermission::ParseErrorResults(resultCodes, uriPolicies, errorResults); + ASSERT_TRUE(errorResults.size() == 4); + EXPECT_EQ(errorResults[0].uri, infoA.path); + EXPECT_EQ(errorResults[0].code, PolicyErrorCode::PERSISTENCE_FORBIDDEN); + EXPECT_EQ(errorResults[1].uri, infoB.path); + EXPECT_EQ(errorResults[1].code, PolicyErrorCode::INVALID_MODE); + EXPECT_EQ(errorResults[2].uri, infoC.path); + EXPECT_EQ(errorResults[2].code, PolicyErrorCode::INVALID_PATH); + EXPECT_EQ(errorResults[3].uri, infoD.path); + EXPECT_EQ(errorResults[3].code, PolicyErrorCode::PERMISSION_NOT_PERSISTED); + GTEST_LOG_(INFO) << "FileShareTest-end ParseErrorResults_test_002"; +} + #endif } // namespace AppFileService } // namespace OHOS \ No newline at end of file -- Gitee From ba1d9b1a17e5aba393603ba6a3aa139d4d4019df Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Sat, 3 Aug 2024 11:44:45 +0800 Subject: [PATCH 05/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: Ice505654b9b5ff7bf2d7d00ccbd0729b920e2e80 --- .../src/file_permission_test.cpp | 6 +- .../file_share_permission_test.cpp | 115 ++++++++++++++++-- 2 files changed, 107 insertions(+), 14 deletions(-) diff --git a/test/unittest/file_permission_native/src/file_permission_test.cpp b/test/unittest/file_permission_native/src/file_permission_test.cpp index f6172e4c3..0347b1ada 100644 --- a/test/unittest/file_permission_native/src/file_permission_test.cpp +++ b/test/unittest/file_permission_native/src/file_permission_test.cpp @@ -612,13 +612,11 @@ HWTEST_F(FilePermissionTest, CheckPersistentPermission_test_0003, testing::ext:: HWTEST_F(FilePermissionTest, GetPathPolicyInfoFromUriPolicyInfo_test_0001, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "FileShareTest-begin GetPathPolicyInfoFromUriPolicyInfo_test_0001"; - UriPolicyInfo infoA = {.uri = "file://" + BUNDLE_NAME_A + "/storage/001.txt"}; UriPolicyInfo infoB = {.uri = BUNDLE_NAME_A + "/storage/001.txt"}; UriPolicyInfo infoC = {.uri = "file://media/Photo/10/1.jpeg"}; UriPolicyInfo infoD = {.uri = "file://" + BUNDLE_NAME_A + "/storage/001.txt?networkid=5454541547878787878748748"}; UriPolicyInfo infoE = {.uri = "file://" + BUNDLE_NAME_A + "/storage"}; std::vector uriPolicies; - uriPolicies.emplace_back(infoA); uriPolicies.emplace_back(infoB); uriPolicies.emplace_back(infoC); uriPolicies.emplace_back(infoD); @@ -627,8 +625,8 @@ HWTEST_F(FilePermissionTest, GetPathPolicyInfoFromUriPolicyInfo_test_0001, testi auto pathPolicies = FilePermission::GetPathPolicyInfoFromUriPolicyInfo(uriPolicies, errorResult); EXPECT_EQ(pathPolicies.size(), 1); EXPECT_EQ(pathPolicies[0].path, "/storage"); - ASSERT_TRUE(errorResult.size() == 5); - EXPECT_EQ(errorResult[4], true); + ASSERT_TRUE(errorResult.size() == 4); + EXPECT_EQ(errorResult[3], true); GTEST_LOG_(INFO) << "FileShareTest-end GetPathPolicyInfoFromUriPolicyInfo_test_0001"; } diff --git a/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp index d7c5a1c2d..0ac913e39 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp +++ b/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp @@ -27,6 +27,7 @@ #include "accesstoken_kit.h" #include "common_func.h" #include "error_code.h" +#include "file_permission.h" #include "ipc_skeleton.h" #include "log.h" #include "oh_file_share.h" @@ -149,7 +150,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_002, Te } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -169,11 +170,29 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_002, Te HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_003, TestSize.Level1) { GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 start"; - FileShare_PolicyInfo *policies = nullptr; unsigned int policiesNum = SET_ZERO; FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; - FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(nullptr, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + ret = OH_FileShare_PersistPermission(policies, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 end"; @@ -210,7 +229,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_004, Te } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -282,7 +301,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_002, Tes } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -308,6 +327,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_003, Tes unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test_003 end"; } @@ -352,7 +390,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_004, Tes } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -424,7 +462,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_002, T } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -450,6 +488,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_003, T unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test_003 end"; } @@ -494,7 +551,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_004, T } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -574,7 +631,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_002, } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -600,6 +657,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_003, unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test_003 end"; } @@ -651,7 +727,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_004, } else { EXPECT_EQ(ret, E_EPERM); if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { EXPECT_FALSE(true); } @@ -761,6 +837,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); if (result != nullptr) { free(result); } -- Gitee From d104c2a517af9ab8e2861b775fd11fb292c4f372 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=99=9F=E9=92=B0?= Date: Tue, 30 Jul 2024 14:19:57 +0800 Subject: [PATCH 06/53] check err MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张晟钰 --- .../native/backup_ext/src/ext_extension.cpp | 57 ++++++++++++++----- 1 file changed, 42 insertions(+), 15 deletions(-) diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index e33ff118a..9c2b9926f 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -604,9 +604,17 @@ int BackupExtExtension::DoRestore(const string &fileName) // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - UntarFile::GetInstance().UnPacket(tarName, path); + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, path); + if (err != 0) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } } else { - UntarFile::GetInstance().UnPacket(tarName, "/"); + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, "/"); + if (err != 0) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } } HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); @@ -638,6 +646,7 @@ int BackupExtExtension::DoIncrementalRestore() } auto fileSet = GetIdxFileData(); auto extManageInfo = GetExtManageInfo(); + ErrCode err = ERR_OK; for (auto item : fileSet) { // 处理要解压的tar文件 if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo)) { if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { @@ -650,14 +659,14 @@ int BackupExtExtension::DoIncrementalRestore() // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); + err = UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); } else { - UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); + err = UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); } HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); } } - return ERR_OK; + return err; } void BackupExtExtension::AsyncTaskBackup(const string config) @@ -731,8 +740,11 @@ static ErrCode RestoreTarForSpecialCloneCloud(ExtManageInfo item) if (untarPath.back() != BConstants::FILE_SEPARATOR_CHAR) { untarPath += BConstants::FILE_SEPARATOR_CHAR; } - UntarFile::GetInstance().UnPacket(tarName, untarPath); - + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, untarPath); + if (err != ERR_OK) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } if (!RemoveFile(tarName)) { HILOGE("Failed to delete the backup tar %{public}s", tarName.c_str()); } @@ -1116,7 +1128,10 @@ void BackupExtExtension::AsyncTaskRestoreForUpgrade() try { auto callBackupEx = ptr->RestoreResultCallbackEx(obj); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); - HILOGI("OnRestore done err = %{public}d", err); + if (err != ERR_OK) { + ptr->AppDone(BError::GetCodeByErrno(err)); + ptr->DoClear(); + } } catch (const BError &e) { ptr->AppDone(e.GetCode()); ptr->DoClear(); @@ -1170,7 +1185,11 @@ void BackupExtExtension::AsyncTaskIncrementalRestoreForUpgrade() try { auto callBackupEx = ptr->IncRestoreResultCallbackEx(obj); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); - HILOGI("OnRestore done err = %{public}d", err); + if (err != ERR_OK) { + HILOGE("OnRestore done, err = %{pubilc}d", err); + ptr->AppIncrementalDone(BError::GetCodeByErrno(err)); + ptr->DoClear(); + } } catch (const BError &e) { ptr->AppIncrementalDone(e.GetCode()); ptr->DoClear(); @@ -1268,7 +1287,11 @@ void BackupExtExtension::AsyncTaskOnBackup() BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { auto callBackupEx = ptr->HandleTaskBackupEx(obj); - ptr->extension_->OnBackup(callBackup, callBackupEx); + ErrCode err = ptr->extension_->OnBackup(callBackup, callBackupEx); + if (err != ERR_OK) { + HILOGE("OnBackup done, err = %{pubilc}d", err); + ptr->AppDone(BError::GetCodeByErrno(err)); + } } catch (const BError &e) { ptr->AppDone(e.GetCode()); } catch (const exception &e) { @@ -1638,7 +1661,11 @@ void BackupExtExtension::AsyncTaskOnIncrementalBackup() BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { auto callBackupEx = ptr->HandleBackupEx(obj); - ptr->extension_->OnBackup(callBackup, callBackupEx); + ErrCode err = ptr->extension_->OnBackup(callBackup, callBackupEx); + if (err != ERR_OK) { + HILOGE("OnBackup done, err = %{pubilc}d", err); + ptr->AppIncrementalDone(BError::GetCodeByErrno(err)); + } } catch (const BError &e) { ptr->AppIncrementalDone(e.GetCode()); } catch (const exception &e) { @@ -1770,9 +1797,9 @@ int BackupExtExtension::DoIncrementalBackup(const vector if (smallFiles.size() == 0 && bigFiles.size() == 0) { // 没有增量,则不需要上传 TarMap tMap; - IncrementalAllFileReady(tMap, allFiles, proxy); + ErrCode err = IncrementalAllFileReady(tMap, allFiles, proxy); HILOGI("Do increment backup, IncrementalAllFileReady end, file empty"); - return ERR_OK; + return err; } // tar包数据 TarMap tarMap; @@ -1784,10 +1811,10 @@ int BackupExtExtension::DoIncrementalBackup(const vector HILOGI("Do increment backup, IncrementalBigFileReady end"); bigMap.insert(tarMap.begin(), tarMap.end()); // 回传manage.json和全量文件 - IncrementalAllFileReady(bigMap, allFiles, proxy); + ErrCode err = IncrementalAllFileReady(bigMap, allFiles, proxy); HILOGI("End, bigFiles num:%{public}zu, smallFiles num:%{public}zu, allFiles num:%{public}zu", bigFiles.size(), smallFiles.size(), allFiles.size()); - return ERR_OK; + return err; } void BackupExtExtension::AppIncrementalDone(ErrCode errCode) -- Gitee From 08f567ce99ed785c5e385327e2c68d349ca760a4 Mon Sep 17 00:00:00 2001 From: g00613291 Date: Thu, 1 Aug 2024 22:27:48 +0800 Subject: [PATCH 07/53] remove restoreDeps & add log --- .../native/backup_ext/src/ext_extension.cpp | 2 +- .../backup_sa/include/module_ipc/service.h | 10 +++ services/backup_sa/src/module_ipc/service.cpp | 70 ++++++++++++------- .../module_ipc/svc_restore_deps_manager.cpp | 16 ++--- .../src/module_ipc/svc_session_manager.cpp | 1 + .../svc_restore_deps_manager_test.cpp | 4 +- utils/src/b_filesystem/b_dir.cpp | 1 + utils/src/b_filesystem/b_file.cpp | 4 +- 8 files changed, 65 insertions(+), 43 deletions(-) diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 071569fdd..ee798ff87 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -268,7 +268,7 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) if (extension_->SpecialVersionForCloneAndCloud()) { return GetIncreFileHandleForSpecialVersion(fileName); } - HILOGI("extension: single to single fileName:%{public}s", fileName.c_str()); + HILOGI("extension: single to single fileName:%{public}s", GetAnonyPath(fileName).c_str()); string path = GetIncrementalFileHandlePath(); string tarName = path + fileName; if (access(tarName.c_str(), F_OK) == 0) { diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 7f8101732..1b6598915 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -318,6 +318,16 @@ private: std::map> &bundleNameDetailMap, RestoreTypeEnum restoreType); + /** + * @brief set session info + * + * @param restoreBundleInfos: bundles to be restored + * @param restoreBundleNames: bundles info to be restored + * @param restoreType: retore type + */ + void SetCurrentSessProperties(std::vector &restoreBundleInfos, + std::vector &restoreBundleNames, RestoreTypeEnum restoreType); + /** * @brief 通知权限模块 * diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 89cc57610..bbbd765cb 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -420,6 +420,33 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector &restoreBundleInfos, + std::vector &restoreBundleNames, RestoreTypeEnum restoreType) +{ + HILOGI("Start"); + for (auto restoreInfo : restoreBundleInfos) { + auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), + [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); + if (it == restoreBundleNames.end()) { + throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); + } + HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), + restoreInfo.extensionName.c_str()); + if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || + (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { + OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); + session_->RemoveExtInfo(restoreInfo.name); + continue; + } + session_->SetBundleRestoreType(restoreInfo.name, restoreType); + session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); + session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); + session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); + session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); + } + HILOGI("End"); +} + ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector &bundleNames, RestoreTypeEnum restoreType, @@ -434,41 +461,26 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, VerifyCaller(IServiceReverse::Scenario::RESTORE); auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); + HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); if (restoreBundleNames.empty()) { session_->DecreaseSessionCnt(); HILOGW("RestoreBundleNames is empty."); return BError(BError::Codes::OK); } session_->AppendBundles(restoreBundleNames); - for (auto restoreInfo : restoreInfos) { - auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), - [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); - if (it == restoreBundleNames.end()) { - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); - } - HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), - restoreInfo.extensionName.c_str()); - if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || - (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { - OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); - session_->RemoveExtInfo(restoreInfo.name); - continue; - } - session_->SetBundleRestoreType(restoreInfo.name, restoreType); - session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); - session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); - session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); - session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); - } + SetCurrentSessProperties(restoreInfos, restoreBundleNames, restoreType); OnStartSched(); session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); } catch (const BError &e) { + HILOGE("Catch exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); return e.GetCode(); } catch (...) { + HILOGE("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); - HILOGI("Unexpected exception"); return EPERM; } } @@ -537,16 +549,19 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); } catch (const BError &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (const exception &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); - HILOGI("Unexpected exception"); + HILOGE("Unexpected exception"); return EPERM; } } @@ -583,16 +598,19 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); HILOGE("Failed, errCode = %{public}d", e.GetCode()); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(); return e.GetCode(); } catch (const exception &e) { - session_->DecreaseSessionCnt(); HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(); return EPERM; } catch(...) { - session_->DecreaseSessionCnt(); HILOGE("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(); return EPERM; } } diff --git a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp index 115db71c4..94bb23b36 100644 --- a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp @@ -28,23 +28,15 @@ vector SvcRestoreDepsManager::GetRestoreBundleNames(const vector lock(lock_); if (impl_.scenario != scenario) { + HILOGE("Inconsistent scenario, impl scenario:%{public}d", impl_.scenario); throw BError(BError::Codes::SDK_MIXED_SCENARIO); } if (impl_.clientToken != clientToken) { diff --git a/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp index cdbfc6036..456188685 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp @@ -107,8 +107,8 @@ HWTEST_F(SvcRestoreDepsManagerTest, SUB_SvcRestoreDepsManager_GetRestoreBundleNa vector bundleInfos {info1, info2}; RestoreTypeEnum restoreType = RESTORE_DATA_WAIT_SEND; auto bundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(bundleInfos, restoreType); - EXPECT_EQ(bundleNames.size(), 1); - EXPECT_FALSE(SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored()); + EXPECT_EQ(bundleNames.size(), 2); + EXPECT_TRUE(SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored()); ClearCache(); GTEST_LOG_(INFO) << "SvcRestoreDepsManagerTest-end SUB_SvcRestoreDepsManager_GetRestoreBundleNames_0200"; } diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index f8c70da1b..23d9b525c 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -40,6 +40,7 @@ static bool IsEmptyDirectory(const string &path) { DIR *dir = opendir(path.c_str()); if (dir == nullptr) { + HILOGE("Opendir failed, errno:%{public}d", errno); return false; } bool isEmpty = true; diff --git a/utils/src/b_filesystem/b_file.cpp b/utils/src/b_filesystem/b_file.cpp index 48b09e6c8..e9d71f8ef 100644 --- a/utils/src/b_filesystem/b_file.cpp +++ b/utils/src/b_filesystem/b_file.cpp @@ -170,8 +170,8 @@ bool BFile::MoveFile(const string &from, const string &to) } newPath.append("/").append(basename(name.get())); if (rename(oldPath.c_str(), newPath.c_str())) { - HILOGE("failed to rename path, oldPath:%{public}s ,newPath: %{public}s", - GetAnonyPath(oldPath).c_str(), GetAnonyPath(newPath).c_str()); + HILOGE("failed to rename path, oldPath: %{public}s, newPath: %{public}s, errno: %{public}d", + GetAnonyPath(oldPath).c_str(), GetAnonyPath(newPath).c_str(), errno); throw BError(errno); } return true; -- Gitee From 317a1c2998f35ee06b9bac14d9620fbda5feb65c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=99=9F=E9=92=B0?= Date: Mon, 5 Aug 2024 16:33:53 +0800 Subject: [PATCH 08/53] =?UTF-8?q?token=E6=A0=A1=E9=AA=8C=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张晟钰 --- .../module_app_gallery/app_gallery_dispose_proxy.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp index 34f60aed3..f49ed5bd3 100644 --- a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp +++ b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp @@ -94,6 +94,11 @@ DisposeErr AppGalleryDisposeProxy::DoDispose(const std::string &bundleName, Disp } MessageParcel data; + const auto interfaceToken = APP_FOUNDATION_SERVICE; + if (!data.WriteInterfaceToken(interfaceToken)) { + HILOGI("write WriteInterfaceToken failed"); + return DisposeErr::IPC_FAIL; + } if (!data.WriteString16(Str8ToStr16(bundleName))) { HILOGI("write ownerInfo and bundleName failed"); return DisposeErr::IPC_FAIL; @@ -103,11 +108,6 @@ DisposeErr AppGalleryDisposeProxy::DoDispose(const std::string &bundleName, Disp HILOGI("write RemoteObject failed"); return DisposeErr::IPC_FAIL; } - const auto interfaceToken = APP_FOUNDATION_SERVICE; - if (!data.WriteInterfaceToken(interfaceToken)) { - HILOGI("write WriteInterfaceToken failed"); - return DisposeErr::IPC_FAIL; - } MessageParcel reply; MessageOption option(MessageOption::TF_ASYNC); -- Gitee From ee361ba8e36f724c6e05cf897c000186e44e6f00 Mon Sep 17 00:00:00 2001 From: g00613291 Date: Sat, 3 Aug 2024 12:25:39 +0800 Subject: [PATCH 09/53] fix sceneBoard restore fail --- .../backup_sa/include/module_ipc/service.h | 2 + .../module_ipc/svc_backup_connection.h | 7 ++++ .../include/module_ipc/svc_session_manager.h | 1 + services/backup_sa/src/module_ipc/service.cpp | 40 +++++++++++-------- .../src/module_ipc/svc_backup_connection.cpp | 12 ++++++ .../src/module_ipc/svc_session_manager.cpp | 16 +++++++- .../src/module_sched/sched_scheduler.cpp | 16 ++++---- .../module_ipc/svc_backup_connection_mock.cpp | 5 +++ 8 files changed, 74 insertions(+), 25 deletions(-) diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 7f8101732..7691b5f7e 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -362,6 +362,8 @@ private: */ void NotifyCallerCurAppIncrementDone(ErrCode errCode, const std::string &callerName); + void SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action); + private: static sptr instance_; static std::mutex instanceLock_; diff --git a/services/backup_sa/include/module_ipc/svc_backup_connection.h b/services/backup_sa/include/module_ipc/svc_backup_connection.h index 379721abd..a8c46591c 100644 --- a/services/backup_sa/include/module_ipc/svc_backup_connection.h +++ b/services/backup_sa/include/module_ipc/svc_backup_connection.h @@ -84,6 +84,11 @@ public: */ void SetCallDied(std::function callDied); + /** + * @brief wait disconnect done + */ + bool WaitDisconnectDone(); + public: SvcBackupConnection(std::function callDied, std::function callConnected) @@ -94,7 +99,9 @@ public: private: std::mutex mutex_; + std::mutex waitMutex_; std::condition_variable condition_; + std::condition_variable waitCondition_; std::atomic isConnected_ = {false}; std::atomic isConnectedDone_ = {false}; sptr backupProxy_; diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h index 737116a6c..5b375c3a9 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -65,6 +65,7 @@ struct BackupExtInfo { std::string backupParameters; int32_t backupPriority; std::string extInfo; + int32_t appendNum {1}; }; class Service; diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 952aeefa0..6d356ea36 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -797,6 +797,25 @@ void Service::NotifyCloneBundleFinish(std::string bundleName) OnAllBundlesFinished(BError(BError::Codes::OK)); } +void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action) +{ + string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */ + HILOGD("BackupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); + string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ + int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */ + RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */ + string bundleExtInfo = session_->GetBackupExtInfo(bundleName); + HILOGI("BundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str()); + + want.SetElementName(bundleName, backupExtName); + want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); + want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); + want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast(restoreType)); + want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName); + want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo); + want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); +} + ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -815,27 +834,16 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) return LaunchBackupSAExtension(bundleName); } AAFwk::Want want; - string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */ - HILOGD("backupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); - string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ - int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */ - RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */ - string bundleExtInfo = session_->GetBackupExtInfo(bundleName); - HILOGI("bundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str()); - - want.SetElementName(bundleName, backupExtName); - want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); - want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); - want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast(restoreType)); - want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName); - want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo); - want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); - + SetWant(want, bundleName, action); auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { HILOGE("LaunchBackupExtension error, backUpConnection is empty"); return BError(BError::Codes::SA_INVAL_ARG); } + if (backUpConnection->IsExtAbilityConnected() && !backUpConnection->WaitDisconnectDone()) { + HILOGE("LaunchBackupExtension error, WaitDisconnectDone failed"); + return BError(BError::Codes::SA_INVAL_ARG); + } ErrCode ret = backUpConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); return ret; } catch (const BError &e) { diff --git a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp index a44451272..befce1a26 100644 --- a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp +++ b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp @@ -79,6 +79,7 @@ void SvcBackupConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName callDied_(move(bundleName)); } condition_.notify_all(); + waitCondition_.notify_all(); HILOGI("called end, name: %{public}s", bundleName.c_str()); } @@ -112,6 +113,17 @@ ErrCode SvcBackupConnection::DisconnectBackupExtAbility() return ret; } +bool SvcBackupConnection::WaitDisconnectDone() +{ + std::unique_lock lock(waitMutex_); + if (waitCondition_.wait_for(lock, std::chrono::seconds(WAIT_TIME), + [this]() { return isConnected_.load() == false; })) { + HILOGI("Wait disconnected done success"); + return true; + } + return false; +} + bool SvcBackupConnection::IsExtAbilityConnected() { return isConnected_.load(); diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index 2ccdb2932..d280d1fc1 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -205,12 +205,18 @@ void SvcSessionManager::RemoveExtInfo(const string &bundleName) unique_lock lock(lock_); auto it = impl_.backupExtNameMap.find(bundleName); if (it == impl_.backupExtNameMap.end()) { + HILOGI("BackupExtNameMap not contain %{public}s", bundleName.c_str()); return; } - impl_.backupExtNameMap.erase(it); if (extConnectNum_) { extConnectNum_--; } + int32_t &appendNum = impl_.backupExtNameMap[bundleName].appendNum; + if (--appendNum > 0) { + HILOGI("No need remove bundleName:%{public}s, appendNum=%{public}d", bundleName.c_str(), appendNum); + return; + } + impl_.backupExtNameMap.erase(it); } wptr SvcSessionManager::GetExtConnection(const BundleName &bundleName) @@ -483,6 +489,14 @@ void SvcSessionManager::AppendBundles(const vector &bundleNames) for (auto &&bundleName : bundleNames) { HILOGD("bundleName: %{public}s", bundleName.c_str()); BackupExtInfo info {}; + auto it = impl_.backupExtNameMap.find(bundleName); + if (it != impl_.backupExtNameMap.end()) { + HILOGI("BackupExtNameMap already contain %{public}s", bundleName.c_str()); + info.backUpConnection = impl_.backupExtNameMap[bundleName].backUpConnection; + info.appendNum = impl_.backupExtNameMap[bundleName].appendNum + 1; + impl_.backupExtNameMap[bundleName] = info; + continue; + } if (SAUtils::IsSABundleName(bundleName)) { info.saBackupConnection = GetBackupSAExt(bundleName); } else { diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp index 726c742d4..910b1e4f7 100644 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ b/services/backup_sa/src/module_sched/sched_scheduler.cpp @@ -72,14 +72,13 @@ void SchedScheduler::Sched(string bundleName) void SchedScheduler::ExecutingQueueTasks(const string &bundleName) { - HILOGE("start"); if (sessionPtr_ == nullptr) { HILOGE("ExecutingQueueTasks bundle %{public}s error, sessionPtr is empty", bundleName.c_str()); return; } BConstants::ServiceSchedAction action = sessionPtr_->GetServiceSchedAction(bundleName); if (action == BConstants::ServiceSchedAction::START) { - // 注册启动定时器 + // register timer for connect extension auto callStart = [reversePtr {reversePtr_}, bundleName]() { HILOGE("Extension connect failed = %{public}s", bundleName.data()); auto ptr = reversePtr.promote(); @@ -91,9 +90,12 @@ void SchedScheduler::ExecutingQueueTasks(const string &bundleName) unique_lock lock(lock_); bundleTimeVec_.emplace_back(make_tuple(bundleName, iTime)); lock.unlock(); - // 启动extension + // launch extension if (reversePtr_ != nullptr) { - reversePtr_->LaunchBackupExtension(bundleName); + ErrCode errCode = reversePtr_->LaunchBackupExtension(bundleName); + if (errCode) { + reversePtr_->ExtConnectFailed(bundleName, errCode); + } } } else if (action == BConstants::ServiceSchedAction::RUNNING) { HILOGI("Current bundle %{public}s process is running", bundleName.data()); @@ -106,12 +108,10 @@ void SchedScheduler::ExecutingQueueTasks(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "Failed to find timer"); } auto &[bName, iTime] = *iter; - // 移除启动定时器 当前逻辑无启动成功后的ext心跳检测 + // unregister timer extTime_.Unregister(iTime); lock.unlock(); - // 开始执行备份恢复流程 - HILOGI("Current bundle %{public}s extension start", bundleName.data()); - //通知应用市场设置处置 + //notify AppGallery to start restore if (reversePtr_ != nullptr) { reversePtr_->SendStartAppGalleryNotify(bundleName); reversePtr_->ExtStart(bundleName); diff --git a/tests/mock/module_ipc/svc_backup_connection_mock.cpp b/tests/mock/module_ipc/svc_backup_connection_mock.cpp index 1d007fa7c..0af352b4e 100644 --- a/tests/mock/module_ipc/svc_backup_connection_mock.cpp +++ b/tests/mock/module_ipc/svc_backup_connection_mock.cpp @@ -55,6 +55,11 @@ ErrCode SvcBackupConnection::DisconnectBackupExtAbility() return 0; } +bool SvcBackupConnection::WaitDisconnectDone() +{ + return true; +} + bool SvcBackupConnection::IsExtAbilityConnected() { bool bFlag = g_bExtAbilityConnected; -- Gitee From cb2b7fe3f0c8469aff3598c08d654c1ab0ea642e Mon Sep 17 00:00:00 2001 From: chen0088 Date: Sat, 3 Aug 2024 16:27:36 +0800 Subject: [PATCH 10/53] add ut Signed-off-by: chen0088 --- .../tools_op_restore_async_test.cpp | 160 ++++++++++++- .../backup_tool/tools_op_restore_test.cpp | 225 +++++++++++++++++- 2 files changed, 377 insertions(+), 8 deletions(-) diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp index c7f7a7b9e..cc797c548 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -293,6 +293,32 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0400, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0400"; } +/** + * @tc.number: SUB_backup_tools_op_restore_async_0401 + * @tc.name: tools_op_restore_async_0401 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9JNFM + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0401, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_0401"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "testBundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0401"; +} + /** * @tc.number: SUB_backup_tools_op_restore_async_0500 * @tc.name: tools_op_restore_async_0500 @@ -318,6 +344,32 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0500, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0500"; } +/** + * @tc.number: SUB_backup_tools_op_restore_async_0501 + * @tc.name: tools_op_restore_async_0501 + * @tc.desc: 测试OnBundleFinished方法 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9JNFM + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_0501"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "testBundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0501"; +} + /** * @tc.number: SUB_backup_tools_op_restore_async_0600 * @tc.name: tools_op_restore_async_0600 @@ -452,8 +504,9 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1001, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1001"; try { vector bundleNames; - bundleNames.push_back("bundle/name");\ + bundleNames.push_back("bundle/name"); shared_ptr restore = make_shared(); + restore->session_ = {}; RestoreApp(restore, bundleNames); } catch (BError &e) { EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); @@ -479,8 +532,9 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1002, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1002"; try { vector bundleNames; - bundleNames.push_back("bundlename");\ + bundleNames.push_back("bundlename"); shared_ptr restore = make_shared(); + restore->session_ = {}; RestoreApp(restore, bundleNames); } catch (BError &e) { EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); @@ -508,7 +562,7 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1100, testing::ext::Tes string pathCapFile = "/data/user/0/test/files/bundleInfo.json"; vector bundleNames = {"bundlenames"}; string type = "false"; - int32_t ret =ChangeBundleInfo(pathCapFile, bundleNames, type); + int32_t ret = ChangeBundleInfo(pathCapFile, bundleNames, type); EXPECT_LT(ret, 0); } catch (...) { EXPECT_TRUE(false); @@ -533,7 +587,7 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1101, testing::ext::Tes string pathCapFile = " "; vector bundleNames = {"bundlenames"}; string type = "false"; - int32_t ret =ChangeBundleInfo(pathCapFile, bundleNames, type); + int32_t ret = ChangeBundleInfo(pathCapFile, bundleNames, type); EXPECT_LT(ret, 0); } catch (...) { EXPECT_TRUE(false); @@ -558,7 +612,7 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1102, testing::ext::Tes string pathCapFile = "/data/user/0/test/files/bundleInfo.json"; vector bundleNames = {}; string type = "true"; - int32_t ret =ChangeBundleInfo(pathCapFile, bundleNames, type); + int32_t ret = ChangeBundleInfo(pathCapFile, bundleNames, type); EXPECT_LT(ret, 0); } catch (...) { EXPECT_TRUE(false); @@ -768,7 +822,6 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1401, testing::ext::Tes { GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1401"; try { - map> mapArgToVal; int ret = Exec(mapArgToVal); EXPECT_EQ(ret, -EPERM); @@ -778,4 +831,97 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1401, testing::ext::Tes } GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1401"; } + +/** + * @tc.number: SUB_backup_tools_op_restore_async_1500 + * @tc.name: tools_op_restore_async_1500 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1500, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1500"; + try { + std::string path = "/data/backup/receive"; + std::vector pkgInfo; + ExtManageInfo info; + info.hashName = "hashName"; + info.fileName = "fileName"; + info.isBigFile = false; + info.isUserTar = false; + pkgInfo.push_back(info); + + auto result = ReadyExtManage(path, pkgInfo); + EXPECT_EQ(result.size(), 1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1500"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_async_1501 + * @tc.name: tools_op_restore_async_1501 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1501"; + try { + std::string path = "/data/backup/receive"; + std::vector pkgInfo; + ExtManageInfo info; + info.hashName = ""; + info.fileName = ""; + info.isBigFile = false; + info.isUserTar = false; + pkgInfo.push_back(info); + + auto result = ReadyExtManage(path, pkgInfo); + EXPECT_EQ(result.size(), 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1501"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_async_1502 + * @tc.name: tools_op_restore_async_1502 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1502, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1502"; + try { + std::string path = "/data/backup/receive"; + std::vector pkgInfo; + ExtManageInfo info; + info.hashName = "hashName"; + info.fileName = "fileName"; + info.isBigFile = true; + info.isUserTar = true; + pkgInfo.push_back(info); + + auto result = ReadyExtManage(path, pkgInfo); + EXPECT_EQ(result.size(), 1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1502"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp index 3d7220db8..7f594449e 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -432,6 +432,129 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleStarted_0601, testing::ext GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleStarted_0601"; } +/** + * @tc.number: SUB_backup_tools_op_restore_0700 + * @tc.name: tools_op_restore_OnBundleFinished_0700 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0700, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0700"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = 0; + BundleName name = BUNDLE_NAME; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0700"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0701 + * @tc.name: tools_op_restore_OnBundleFinished_0701 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0701, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0701"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = BUNDLE_NAME; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0701"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0702 + * @tc.name: tools_op_restore_OnBundleFinished_0702 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0702, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0702"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0702"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0703 + * @tc.name: tools_op_restore_OnBundleFinished_0703 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0703, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0703"; + try { + auto ctx = make_shared(); + ErrCode err = -1; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0703"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0704 + * @tc.name: tools_op_restore_OnBundleFinished_0704 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0704, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0704"; + try { + auto ctx = make_shared(); + OnBackupServiceDied(ctx); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0704"; +} + /** * @tc.number: SUB_backup_tools_op_restore_0800 * @tc.name: tools_op_restore_OnResultReport_0800 @@ -639,6 +762,31 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitRestoreSession_1100, testing:: GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_GInitRestoreSession_1100"; } +/** + * @tc.number: SUB_backup_tools_op_restore_1101 + * @tc.name: tools_op_restore_InitRestoreSession_1101 + * @tc.desc: 测试当ctx + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitRestoreSession_1101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_InitRestoreSession_1101"; + try { + shared_ptr ctx = make_shared(); + InitRestoreSession(ctx); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitRestoreSession_1101"; +} + /** * @tc.number: SUB_backup_tools_op_restore_1200 * @tc.name: tools_op_restore_InitPathCapFile_1200 @@ -664,6 +812,56 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitPathCapFile_1200, testing::ext GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitPathCapFile_1200"; } +/** + * @tc.number: SUB_backup_tools_op_restore_1201 + * @tc.name: tools_op_restore_InitPathCapFile_1201 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitPathCapFile_1201, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_InitPathCapFile_1201"; + try { + string pathCapFile = "/data/backup/tmp"; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = true; + int32_t ret = InitPathCapFile(pathCapFile, bundleNames, depMode); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitPathCapFile_1201"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_1202 + * @tc.name: tools_op_restore_InitPathCapFile_1202 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitPathCapFile_1202, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_InitPathCapFile_1202"; + try { + string pathCapFile = "/data/backup/tmp"; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = false; + int32_t ret = InitPathCapFile(pathCapFile, bundleNames, depMode); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitPathCapFile_1202"; +} + /** * @tc.number: SUB_backup_tools_op_restore_1300 * @tc.name: tools_op_restore_Exec_1300 @@ -767,4 +965,29 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_Exec_1303, testing::ext::TestSize. } GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_Exec_1303"; } + +/** + * @tc.number: SUB_backup_tools_op_restore_1304 + * @tc.name: tools_op_restore_Exec_1304 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_Exec_1304, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_Exec_1304"; + try { + map> mapArgToVal; + mapArgToVal["pathCapFile"] = {"/data/backup/recived/com.example.app2backup/"}; + mapArgToVal["bundles"] = {"com.example.app2backup/"}; + int ret = Exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_Exec_1304"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From e9491655cd461d0255eb77bd1347d741f1dc4e84 Mon Sep 17 00:00:00 2001 From: libo429 Date: Tue, 6 Aug 2024 12:57:05 +0800 Subject: [PATCH 11/53] Call timing control Signed-off-by: libo429 --- .../src/b_incremental_backup_session.cpp | 5 + .../src/b_incremental_restore_session.cpp | 5 + .../b_incremental_session_restore_async.cpp | 5 + .../backup_kit_inner/src/b_session_backup.cpp | 5 + .../src/b_session_restore.cpp | 5 + .../src/b_session_restore_async.cpp | 5 + .../backup_sa/include/module_ipc/service.h | 17 ++ .../include/module_ipc/svc_session_manager.h | 2 + services/backup_sa/src/module_ipc/service.cpp | 170 ++++++++++++------ .../src/module_ipc/svc_session_manager.cpp | 16 ++ .../module_ipc/svc_session_manager_mock.cpp | 5 + .../svc_session_manager_throw_mock.cpp | 5 + .../svc_session_manager_throw_mock.h | 2 + .../session/b_incremental_session_test.cpp | 3 + utils/include/b_json/b_json_entity_caps.h | 4 +- utils/src/b_json/b_report_entity.cpp | 3 +- 16 files changed, 198 insertions(+), 59 deletions(-) diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp index f747d28c7..28928068b 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp @@ -113,6 +113,11 @@ ErrCode BIncrementalBackupSession::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp index 000241ad0..68f48d2ab 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp @@ -119,6 +119,11 @@ ErrCode BIncrementalRestoreSession::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp index 84f75d66e..109350dec 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp @@ -125,6 +125,11 @@ ErrCode BIncrementalSessionRestoreAsync::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index 04176686b..78c19fec8 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -132,6 +132,11 @@ ErrCode BSessionBackup::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp index 250d68bc7..e2063e27e 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -130,6 +130,11 @@ ErrCode BSessionRestore::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp index 10c388fb5..e44e65b6f 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp @@ -125,6 +125,11 @@ ErrCode BSessionRestoreAsync::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index b1830fdaf..a3a7d7b0a 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -173,6 +173,13 @@ public: * */ void SessionDeactive(); + + /** + * @brief 卸载服务 + * + */ + void UnloadService(); + /** * @brief 构造拉起应用所需的want * @@ -374,6 +381,15 @@ private: void SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action); + /** + * @brief GetBackupInfo 任务执行 + * + * @param bundleName 应用名称 + * @param result 业务结果出参 + * + */ + ErrCode GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result); + private: static sptr instance_; static std::mutex instanceLock_; @@ -381,6 +397,7 @@ private: std::condition_variable getBackupInfoCondition_; static inline std::atomic seed {1}; std::atomic isConnectDied_ {false}; + std::atomic isUnloadService_ {false}; sptr session_; sptr sched_; diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h index 5b375c3a9..bdb674fed 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -476,6 +476,7 @@ public: bool ValidRestoreDataType(RestoreTypeEnum restoreType); Impl GetImpl(); + int GetSessionCnt(); private: /** @@ -542,6 +543,7 @@ private: uint32_t extConnectNum_ {0}; Utils::Timer extBundleTimer {"backupBundleExtTimer"}; std::atomic sessionCnt_ {0}; + bool unloadSAFlag_ {false}; int32_t memoryParaCurSize_ {BConstants::DEFAULT_VFS_CACHE_PRESSURE}; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index cd8b32020..a896ceb52 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -144,6 +144,10 @@ UniqueFd Service::GetLocalCapabilities() so there must be set init userId. */ HILOGI("Begin"); + if (session_ == nullptr) { + HILOGE("GetLocalCapabilities error, session is empty."); + return UniqueFd(-EPERM); + } session_->IncreaseSessionCnt(); session_->SetSessionUserId(GetUserIdDefault()); VerifyCaller(); @@ -152,7 +156,8 @@ UniqueFd Service::GetLocalCapabilities() UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR)); if (fd < 0) { HILOGE("Failed to open config file = %{private}s, err = %{public}d", path.c_str(), errno); - return UniqueFd(-1); + session_->DecreaseSessionCnt(); + return UniqueFd(-EPERM); } BJsonCachedEntity cachedEntity(std::move(fd)); @@ -1374,6 +1379,18 @@ void Service::DeleteDisConfigFile() } } +void Service::UnloadService() +{ + if (sched_ == nullptr) { + HILOGE("Unload Service error, sched is empty"); + return; + } + if (!isUnloadService_.load()) { + isUnloadService_.store(true); + sched_->TryUnloadService(); + } +} + void Service::SessionDeactive() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -1394,8 +1411,12 @@ void Service::SessionDeactive() return; } session_->ClearSessionData(); - // 卸载服务 - sched_->TryUnloadService(); + // close session + StopAll(nullptr, true); + if (session_->GetSessionCnt() <= 0) { + HILOGI("do unload Service."); + sched_->TryUnloadService(); + } } catch (...) { HILOGE("Unexpected exception"); return; @@ -1429,51 +1450,66 @@ std::function Service::GetBackupInfoConnectDied(wptr }; } +ErrCode Service::GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result) +{ + if (session_ == nullptr) { + HILOGE("Get BackupInfo error, session is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->SetSessionUserId(GetUserIdDefault()); + auto backupConnection = session_->CreateBackupConnection(bundleName); + if (backupConnection == nullptr) { + HILOGE("backupConnection is null. bundleName: %{public}s", bundleName.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName); + auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName); + backupConnection->SetCallback(callConnected); + backupConnection->SetCallDied(callDied); + AAFwk::Want want = CreateConnectWant(bundleName); + auto ret = backupConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); + if (ret) { + HILOGE("ConnectBackupExtAbility faild, please check bundleName: %{public}s", bundleName.c_str()); + return BError(BError::Codes::EXT_ABILITY_DIED); + } + std::unique_lock lock(getBackupInfoMutx_); + getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S)); + if (isConnectDied_.load()) { + HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str()); + isConnectDied_.store(false); + return BError(BError::Codes::EXT_ABILITY_DIED); + } + auto proxy = backupConnection->GetBackupExtProxy(); + if (!proxy) { + HILOGE("Extension backup Proxy is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } + ret = proxy->GetBackupInfo(result); + backupConnection->DisconnectBackupExtAbility(); + if (ret != ERR_OK) { + HILOGE("Call Ext GetBackupInfo faild."); + return BError(BError::Codes::SA_INVAL_ARG); + } + + return BError(BError::Codes::OK); +} + ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result) { try { HILOGI("Service::GetBackupInfo begin."); + if (session_ == nullptr) { + HILOGE("Get BackupInfo error, session is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } if (session_->GetImpl().clientToken) { return BError(BError::Codes::SA_REFUSED_ACT, "Already have an active session"); } session_->IncreaseSessionCnt(); - session_->SetSessionUserId(GetUserIdDefault()); - auto backupConnection = session_->CreateBackupConnection(bundleName); - if (backupConnection == nullptr) { - HILOGE("backupConnection is null. bundleName: %{public}s", bundleName.c_str()); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName); - auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName); - backupConnection->SetCallback(callConnected); - backupConnection->SetCallDied(callDied); - AAFwk::Want want = CreateConnectWant(bundleName); - auto ret = backupConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); - if (ret) { - HILOGE("ConnectBackupExtAbility faild, please check bundleName: %{public}s", bundleName.c_str()); - return BError(BError::Codes::EXT_ABILITY_DIED); - } - std::unique_lock lock(getBackupInfoMutx_); - getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S)); - if (isConnectDied_.load()) { - HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str()); - isConnectDied_.store(false); - return BError(BError::Codes::EXT_ABILITY_DIED); - } - auto proxy = backupConnection->GetBackupExtProxy(); - if (!proxy) { - HILOGE("Extension backup Proxy is empty."); - return BError(BError::Codes::SA_INVAL_ARG); - } - ret = proxy->GetBackupInfo(result); - backupConnection->DisconnectBackupExtAbility(); - if (ret != ERR_OK) { - HILOGE("Call Ext GetBackupInfo faild."); - return BError(BError::Codes::SA_INVAL_ARG); - } + auto ret = GetBackupInfoCmdHandle(bundleName, result); HILOGI("Service::GetBackupInfo end. result: %s", result.c_str()); session_->DecreaseSessionCnt(); - return BError(BError::Codes::OK); + return ret; } catch (...) { session_->DecreaseSessionCnt(); HILOGI("Unexpected exception"); @@ -1509,8 +1545,13 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res }; try { HILOGI("Service::UpdateTimer begin."); - VerifyCaller(); + if (session_ == nullptr) { + HILOGE("Update Timer error, session is empty."); + result = false; + return BError(BError::Codes::SA_INVAL_ARG); + } session_->IncreaseSessionCnt(); + VerifyCaller(); result = session_->UpdateTimer(bundleName, timeOut, timeoutCallback); session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); @@ -1524,25 +1565,42 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) { - HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); - VerifyCaller(); - IServiceReverse::Scenario scenario = session_ -> GetScenario(); - if (scenario != IServiceReverse::Scenario::BACKUP) { - HILOGE("This method is applicable to the backup scenario"); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto backupConnection = session_->GetExtConnection(bundleName); - auto proxy = backupConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); - if (ret != NO_ERROR) { + try { + HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); + if (session_ == nullptr) { + HILOGE("Update Send Rate error, session is empty."); + result = false; + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(); + VerifyCaller(); + IServiceReverse::Scenario scenario = session_ -> GetScenario(); + if (scenario != IServiceReverse::Scenario::BACKUP) { + HILOGE("This method is applicable to the backup scenario"); + result = false; + session_->DecreaseSessionCnt(); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto backupConnection = session_->GetExtConnection(bundleName); + auto proxy = backupConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); + if (ret != NO_ERROR) { + result = false; + session_->DecreaseSessionCnt(); + return BError(BError::Codes::EXT_BROKEN_IPC); + } + result = true; + session_->DecreaseSessionCnt(); + return BError(BError::Codes::OK); + } catch (...) { result = false; - return BError(BError::Codes::EXT_BROKEN_IPC); + session_->DecreaseSessionCnt(); + HILOGI("Unexpected exception"); + return EPERM; } - result = true; - return BError(BError::Codes::OK); } AAFwk::Want Service::CreateConnectWant (BundleName &bundleName) diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index c63dfe403..e2073930a 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -54,6 +54,11 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return impl_; } +int SvcSessionManager::GetSessionCnt() +{ + return sessionCnt_.load(); +} + ErrCode SvcSessionManager::Active(Impl newImpl) { unique_lock lock(lock_); @@ -72,6 +77,7 @@ ErrCode SvcSessionManager::Active(Impl newImpl) InitClient(newImpl); impl_ = newImpl; + unloadSAFlag_ = false; return BError(BError::Codes::OK); } @@ -93,6 +99,7 @@ void SvcSessionManager::Deactive(const wptr &remoteInAction, bool deathRecipient_ = nullptr; HILOGI("Succeed to deactive a session"); impl_ = {}; + unloadSAFlag_ = true; extConnectNum_ = 0; } @@ -744,6 +751,15 @@ void SvcSessionManager::DecreaseSessionCnt() sessionCnt_--; } else { HILOGE("Invalid sessionCount."); + return; + } + if (reversePtr_ == nullptr) { + HILOGE("Service reverse pointer is empty."); + return; + } + if (sessionCnt_.load() <= 0 && unloadSAFlag_ == true) { + HILOGI("do unload Service."); + reversePtr_->UnloadService(); } } diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 320bdd66c..528e46728 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -393,6 +393,11 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return impl_; } +int SvcSessionManager::GetSessionCnt() +{ + return sessionCnt_.load(); +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) {} int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName) diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp index 9ba4687b8..de45882f4 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -275,6 +275,11 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return BackupSvcSessionManager::session->GetImpl(); } +int SvcSessionManager::GetSessionCnt() +{ + return BackupSvcSessionManager::session->GetSessionCnt(); +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) { BackupSvcSessionManager::session->SetIncrementalData(incrementalData); diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.h b/tests/mock/module_ipc/svc_session_manager_throw_mock.h index 670bef53b..633488906 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -78,6 +78,7 @@ public: virtual bool GetIsIncrementalBackup() = 0; virtual bool ValidRestoreDataType(RestoreTypeEnum) = 0; virtual SvcSessionManager::Impl GetImpl() = 0; + virtual int GetSessionCnt() = 0; virtual void SetIncrementalData(const BIncrementalData &) = 0; virtual int32_t GetIncrementalManifestFd(const std::string &) = 0; virtual int64_t GetLastIncrementalTime(const std::string &) = 0; @@ -138,6 +139,7 @@ public: MOCK_METHOD(bool, GetIsIncrementalBackup, ()); MOCK_METHOD(bool, ValidRestoreDataType, (RestoreTypeEnum)); MOCK_METHOD(SvcSessionManager::Impl, GetImpl, ()); + MOCK_METHOD(int, GetSessionCnt, ()); MOCK_METHOD(void, SetIncrementalData, (const BIncrementalData &)); MOCK_METHOD(int32_t, GetIncrementalManifestFd, (const std::string &)); MOCK_METHOD(int64_t, GetLastIncrementalTime, (const std::string &)); diff --git a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp index 9adae7f71..d45ffbda8 100644 --- a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp +++ b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp @@ -168,6 +168,7 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_0400, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); + EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = backupSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); @@ -291,6 +292,7 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_0800, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); + EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = restoreSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); @@ -602,6 +604,7 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_1800, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); + EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = restoreAsyncSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); diff --git a/utils/include/b_json/b_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h index 548beef14..30c38e667 100644 --- a/utils/include/b_json/b_json_entity_caps.h +++ b/utils/include/b_json/b_json_entity_caps.h @@ -146,7 +146,7 @@ public: return obj_["extraInfo"]; } - bool CheckBundlePropertiesIsValid(const Json::Value &bundleInfo) + bool CheckBundlePropertiesValid(const Json::Value &bundleInfo) { if (!bundleInfo) { HILOGE("Failed Check bundleInfo"); @@ -187,7 +187,7 @@ public: } std::vector bundleInfos; for (const auto &item : obj_["bundleInfos"]) { - if (!CheckBundlePropertiesIsValid(item)) { + if (!CheckBundlePropertiesValid(item)) { return {}; } string restoreDeps(""); diff --git a/utils/src/b_json/b_report_entity.cpp b/utils/src/b_json/b_report_entity.cpp index 7acdd932a..fb5d342c1 100644 --- a/utils/src/b_json/b_report_entity.cpp +++ b/utils/src/b_json/b_report_entity.cpp @@ -257,7 +257,8 @@ void BReportEntity::CheckAndUpdateIfReportLineEncoded(std::string &path) } unordered_map infos = GetReportInfos(); - if (infos.size() == 1) { + constexpr int BIG_FILE_REPORT_INFO_NUM = 1; + if (infos.size() == BIG_FILE_REPORT_INFO_NUM) { auto info = infos.begin(); path = info->first; } else { -- Gitee From 11b79bd56e737a9ea57c6e617e58df54828ddd61 Mon Sep 17 00:00:00 2001 From: chen0088 Date: Tue, 6 Aug 2024 15:14:06 +0800 Subject: [PATCH 12/53] add ut Signed-off-by: chen0088 --- tests/unittests/backup_tools/BUILD.gn | 9 +- .../tools_op_incremental_restore_test.cpp | 594 +++++++++++++++++- 2 files changed, 599 insertions(+), 4 deletions(-) diff --git a/tests/unittests/backup_tools/BUILD.gn b/tests/unittests/backup_tools/BUILD.gn index 15fa2bced..b30de9358 100644 --- a/tests/unittests/backup_tools/BUILD.gn +++ b/tests/unittests/backup_tools/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -81,10 +81,14 @@ ohos_unittest("backup_tool_restore_test") { sources = [ "${path_backup_mock}/b_filesystem/b_file_mock.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_restore_mock.cpp", "${path_backup}/tools/backup_tool/src/tools_op.cpp", - "${path_backup}/tools/backup_tool/src/tools_op_incremental_restore.cpp", "backup_tool/tools_op_incremental_restore_test.cpp", "backup_tool/tools_op_restore_async_test.cpp", "backup_tool/tools_op_restore_test.cpp", @@ -93,6 +97,7 @@ ohos_unittest("backup_tool_restore_test") { include_dirs = [ "${path_base}/include", + "${path_backup}/frameworks/native/backup_kit_inner/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", "${path_backup}/interfaces/inner_api/native/backup_kit_inner", "${path_backup}/tools/backup_tool/include", diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp index a5f8038a8..e72348a50 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,7 +21,7 @@ #include "b_resources/b_constants.h" #include "tools_op.h" -#include "tools_op_incremental_restore.h" +#include "tools_op_incremental_restore.cpp" namespace OHOS::FileManagement::Backup { using namespace std; @@ -195,4 +195,594 @@ HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_ } GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_restore_0300"; } + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0400 + * @tc.name: SUB_backup_tools_op_incremental_restore_0400 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0400, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0400"; + try { + auto ctx = make_shared(); + BFileInfo fileInfo; + fileInfo.owner = "test"; + fileInfo.fileName = "/manage.json"; + fileInfo.sn = 1; + UniqueFd fd(open("textFile", O_RDONLY)); + UniqueFd manifestFd(open("textManifest", O_RDONLY)); + OnFileReady(ctx, fileInfo, move(fd), move(manifestFd), 0); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0400"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0500 + * @tc.name: SUB_backup_tools_op_incremental_restore_0500 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0500, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0500"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times = {"100"}; + int32_t ret = InitRestoreSession(ctx, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0500"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0501 + * @tc.name: SUB_backup_tools_op_incremental_restore_0501 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0501"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("100"); + times.push_back("200"); + int32_t ret = InitRestoreSession(nullptr, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0501"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0502 + * @tc.name: SUB_backup_tools_op_incremental_restore_0502 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0502, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0502"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("10"); + times.push_back("20"); + int32_t ret = InitRestoreSession(nullptr, bundleNames, times); + EXPECT_EQ(0, ret); + + BFileInfo fileInfo; + fileInfo.owner = "test"; + fileInfo.fileName = "manage.json"; + fileInfo.sn = 1; + UniqueFd fd(open("textFile", O_RDONLY)); + UniqueFd manifestFd(open("textManifest", O_RDONLY)); + OnFileReady(ctx, fileInfo, move(fd), move(manifestFd), 0); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0502"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0600 + * @tc.name: SUB_backup_tools_op_incremental_restore_0600 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0600, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0600"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0600"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0601 + * @tc.name: SUB_backup_tools_op_incremental_restore_0601 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0601, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0601"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0601"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0700 + * @tc.name: SUB_backup_tools_op_incremental_restore_0700 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0700, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0700"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0700"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0701 + * @tc.name: SUB_backup_tools_op_incremental_restore_0701 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0701, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0701"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "bundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0701"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0800 + * @tc.name: SUB_backup_tools_op_incremental_restore_0800 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0800, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0800"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0800"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0801 + * @tc.name: SUB_backup_tools_op_incremental_restore_0801 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0801, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0801"; + try { + auto ctx = make_shared(); + ErrCode err = -1; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0801"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0900 + * @tc.name: SUB_backup_tools_op_incremental_restore_0900 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0900, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0900"; + try { + auto ctx = make_shared(); + OnBackupServiceDied(ctx); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0900"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1000 + * @tc.name: SUB_backup_tools_op_incremental_restore_1000 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1000"; + try { + shared_ptr restore = nullptr; + RestoreApp(restore); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1000"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1001 + * @tc.name: SUB_backup_tools_op_incremental_restore_1001 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1001"; + try { + shared_ptr restore = make_shared(); + restore->session_ = nullptr; + RestoreApp(restore); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1001"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1002 + * @tc.name: SUB_backup_tools_op_incremental_restore_1002 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1002"; + try { + shared_ptr restore = make_shared(); + restore->session_ = {}; + BIncrementalData data("text", 1); + restore->lastIncrementalData = {data}; + RestoreApp(restore); + EXPECT_TRUE(true); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1002"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1100 + * @tc.name: SUB_backup_tools_op_incremental_restore_1100 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1100"; + try { + string pathCapFile = ""; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = true; + vector times = {"10"}; + int32_t ret = Init(pathCapFile, bundleNames, depMode, times); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1100"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1101 + * @tc.name: SUB_backup_tools_op_incremental_restore_1101 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1101"; + try { + string pathCapFile = "/data/backup"; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = true; + vector times = {"1"}; + int32_t ret = Init(pathCapFile, bundleNames, depMode, times); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1101"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1200 + * @tc.name: SUB_backup_tools_op_incremental_restore_1200 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1200"; + try { + map> mapArgToVal; + mapArgToVal["depMode"] = {"false"}; + g_exec(mapArgToVal); + EXPECT_EQ(mapArgToVal["depMode"][0], "false"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1200"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1201 + * @tc.name: SUB_backup_tools_op_incremental_restore_1201 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1201, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1201"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1201"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1202 + * @tc.name: SUB_backup_tools_op_incremental_restore_1202 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1202, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1202"; + try { + map> mapArgToVal = { + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1202"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1203 + * @tc.name: SUB_backup_tools_op_incremental_restore_1203 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1203, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1203"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}}, + {"depMode", {"true"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1203"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1204 + * @tc.name: SUB_backup_tools_op_incremental_restore_1204 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1204, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1204"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1204"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1205 + * @tc.name: SUB_backup_tools_op_incremental_restore_1205 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1205, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1205"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1205"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From 5e36d39c5a5c3aa3bc49694b1ae56cb39fc7ebd2 Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Wed, 7 Aug 2024 16:01:05 +0800 Subject: [PATCH 13/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: Iec276eac4f3fd29559b75bbfb7f983f7e1158138 --- .../kits/ndk/fileuri/src/oh_file_uri.cpp | 2 +- .../src/file_permission_test.cpp | 1 - .../file_uri_native/file_uri_test.cpp | 29 ++++++ .../file_uri_ndk_test/file_uri_ndk_test.cpp | 95 +++++++++++++++++++ .../include/file_permission_mock.h | 55 +++++++++++ .../src/file_permission_mock.cpp | 65 +++++++++++++ .../parameter_mock/include/parameter_mock.h | 39 ++++++++ .../parameter_mock/src/parameter_mock.cpp | 27 ++++++ 8 files changed, 311 insertions(+), 2 deletions(-) create mode 100644 tests/mock/file_permission_native_mock/include/file_permission_mock.h create mode 100644 tests/mock/file_permission_native_mock/src/file_permission_mock.cpp create mode 100644 tests/mock/parameter_mock/include/parameter_mock.h create mode 100644 tests/mock/parameter_mock/src/parameter_mock.cpp diff --git a/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp b/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp index db175595e..e471696ab 100644 --- a/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp +++ b/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp @@ -84,7 +84,7 @@ FileManagement_ErrCode OH_FileUri_GetFullDirectoryUri(const char *uri, unsigned bool OH_FileUri_IsValidUri(const char *uri, unsigned int length) { if (uri == nullptr || strlen(uri) != length) { - return ERR_PARAMS; + return false; } std::string uriStr(uri, length); OHOS::AppFileService::ModuleFileUri::FileUri fileUri(uriStr); diff --git a/test/unittest/file_permission_native/src/file_permission_test.cpp b/test/unittest/file_permission_native/src/file_permission_test.cpp index 0347b1ada..ac5fd8647 100644 --- a/test/unittest/file_permission_native/src/file_permission_test.cpp +++ b/test/unittest/file_permission_native/src/file_permission_test.cpp @@ -624,7 +624,6 @@ HWTEST_F(FilePermissionTest, GetPathPolicyInfoFromUriPolicyInfo_test_0001, testi vector errorResult; auto pathPolicies = FilePermission::GetPathPolicyInfoFromUriPolicyInfo(uriPolicies, errorResult); EXPECT_EQ(pathPolicies.size(), 1); - EXPECT_EQ(pathPolicies[0].path, "/storage"); ASSERT_TRUE(errorResult.size() == 4); EXPECT_EQ(errorResult[3], true); GTEST_LOG_(INFO) << "FileShareTest-end GetPathPolicyInfoFromUriPolicyInfo_test_0001"; diff --git a/test/unittest/file_uri_native/file_uri_test.cpp b/test/unittest/file_uri_native/file_uri_test.cpp index d02975a69..45b5fe190 100644 --- a/test/unittest/file_uri_native/file_uri_test.cpp +++ b/test/unittest/file_uri_native/file_uri_test.cpp @@ -268,4 +268,33 @@ namespace OHOS::AppFileService::ModuleFileUri { EXPECT_EQ(folderUriObject.GetFullDirectoryUri(), folderDirectoryUri); GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetPath_0000"; } + + /** + * @tc.name: File_uri_IsRemoteUri_0000 + * @tc.desc: Test function of IsRemoteUri() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ + HWTEST_F(FileUriTest, File_uri_IsRemoteUri_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileUriTest-begin File_uri_GetFullDirectoryUri_0000"; + string fileStr = "file://" + BUNDLE_A + "/data/test"; + FileUri fileUriObject(fileStr); + EXPECT_EQ(fileUriObject.IsRemoteUri(), false); + + string fileStr2 = "file://" + BUNDLE_A + "/data/test?networkid="; + FileUri fileUriObject2(fileStr2); + EXPECT_EQ(fileUriObject2.IsRemoteUri(), false); + + string fileStr3 = "file://" + BUNDLE_A + "/data/test?networkid=123456/"; + FileUri fileUriObject3(fileStr3); + EXPECT_EQ(fileUriObject3.IsRemoteUri(), false); + + string fileStr4 = "file://" + BUNDLE_A + "/data/test?networkid=123456"; + FileUri fileUriObject4(fileStr4); + EXPECT_EQ(fileUriObject4.IsRemoteUri(), true); + GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetPath_0000"; + } } \ No newline at end of file diff --git a/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp b/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp index 307dfb9f7..518a285cb 100644 --- a/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp +++ b/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp @@ -223,6 +223,36 @@ HWTEST_F(NDKFileUriTest, get_path_from_uri_test_006, TestSize.Level1) GTEST_LOG_(INFO) << "get_path_from_uri_test_006 end"; } +/** + * @tc.number: get_path_from_uri_test_007 + * @tc.name: Test function of OH_FileUri_GetPathFromUri() interface for distributed files uri + * @tc.desc: Set uri and get path + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, get_path_from_uri_test_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "get_path_from_uri_test_007 start"; + std::string bundleB = "com.example.fileshareb"; + std::string fileUriStr = "file://" + bundleB + "/data/storage/el2/distributedfiles/.remote_share/"; + fileUriStr += "data/storage/el2/base/haps/entry/files/GetPathFromUri006.txt"; + fileUriStr += "?networkid=64799ecdf70788e396f454ff4a6e6ae4b09e20227c39c21f6e67a2aacbcef7b9"; + const char *fileUri = fileUriStr.c_str(); + std::string filePathUri = "/data/storage/el2/share/r/" + bundleB; + filePathUri += "/data/storage/el2/distributedfiles/.remote_share/"; + filePathUri += "data/storage/el2/base/haps/entry/files/GetPathFromUri006.txt"; + char *result = nullptr; + unsigned int length = fileUriStr.size(); + FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(nullptr, length, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetPathFromUri(fileUri, length - 1, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetPathFromUri(fileUri, length, nullptr); + EXPECT_EQ(ret, ERR_PARAMS); + GTEST_LOG_(INFO) << "get_path_from_uri_test_007 end"; +} + /** * @tc.number: get_uri_from_path_test_001 * @tc.name: Test function of OH_FileUri_GetUriFromPath() interface for document uri @@ -246,6 +276,29 @@ HWTEST_F(NDKFileUriTest, get_uri_from_path_test_001, TestSize.Level1) GTEST_LOG_(INFO) << "get_uri_from_path_test_001 end"; } +/** + * @tc.number: get_uri_from_path_test_002 + * @tc.name: Test function of OH_FileUri_GetUriFromPath() interface for document uri + * @tc.desc: Set path and get uri + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, get_uri_from_path_test_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "get_uri_from_path_test_002 start"; + const char filePath[] = "storage/Users/currentUser/Documents/GetPathFromUri001.txt"; + char *result = nullptr; + unsigned int length = strlen(filePath); + FileManagement_ErrCode ret = OH_FileUri_GetUriFromPath(nullptr, length, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetUriFromPath(filePath, length - 1, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetUriFromPath(filePath, length, nullptr); + EXPECT_EQ(ret, ERR_PARAMS); + GTEST_LOG_(INFO) << "get_uri_from_path_test_002 end"; +} + /** * @tc.number: get_full_directory_uri_test_001 * @tc.name: Test function of OH_FileUri_GetFullDirectoryUri() interface for unknown path @@ -287,6 +340,30 @@ HWTEST_F(NDKFileUriTest, get_full_directory_uri_test_002, TestSize.Level1) GTEST_LOG_(INFO) << "get_full_directory_uri_test_002 end"; } +/** + * @tc.number: get_full_directory_uri_test_003 + * @tc.name: Test function of OH_FileUri_GetFullDirectoryUri() interface for success + * @tc.desc: Set uri and get full directory uri + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, get_full_directory_uri_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "get_full_directory_uri_test_003 start"; + const char fileUri[] = "file://com.example.filesharea/data/test/file_uri_test.txt"; + char *result = nullptr; + unsigned int length = strlen(fileUri); + FileManagement_ErrCode ret = OH_FileUri_GetFullDirectoryUri(nullptr, length, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetFullDirectoryUri(fileUri, length - 1, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetFullDirectoryUri(fileUri, length, nullptr); + EXPECT_EQ(ret, ERR_PARAMS); + FreeResult(&result); + GTEST_LOG_(INFO) << "get_full_directory_uri_test_003 end"; +} + /** * @tc.number: is_valid_uri_test_001 * @tc.name: Test function of OH_FileUri_IsValidUri() interface for real uri @@ -319,4 +396,22 @@ HWTEST_F(NDKFileUriTest, is_valid_uri_test_002, TestSize.Level1) GTEST_LOG_(INFO) << "is_valid_uri_test_002"; } +/** + * @tc.number: is_valid_uri_test_003 + * @tc.name: Test function of OH_FileUri_IsValidUri() interface for unreal uri + * @tc.desc: Set URI and make a judgment + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, is_valid_uri_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "is_valid_uri_test_003"; + const char fileUri[] = "com.demo.a/data/storage/el2/base/files/IsValidUriTest002.txt"; + unsigned int length = strlen(fileUri); + bool flags = OH_FileUri_IsValidUri(nullptr, length); + EXPECT_EQ(flags, false); + + flags = OH_FileUri_IsValidUri(nullptr, length - 1); + EXPECT_EQ(flags, false); + GTEST_LOG_(INFO) << "is_valid_uri_test_003"; +} } // namespace OHOS::AppFileService::ModuleFileUri \ No newline at end of file diff --git a/tests/mock/file_permission_native_mock/include/file_permission_mock.h b/tests/mock/file_permission_native_mock/include/file_permission_mock.h new file mode 100644 index 000000000..199421815 --- /dev/null +++ b/tests/mock/file_permission_native_mock/include/file_permission_mock.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef FILEMANAGEMENT_FILE_PERMISSION_MOCK_MOCK_H +#define FILEMANAGEMENT_FILE_PERMISSION_MOCK_MOCK_H +#include + +#include "file_permission.h" +namespace OHOS { +namespace AppFileService { +class IFilePermissionMock { +public: + virtual ~IFilePermissionMock() = default; + virtual int32_t PersistPermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t RevokePermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t ActivatePermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t DeactivatePermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t CheckPersistentPermission(const vector &uriPolicies, + vector &errorResults) = 0; +public: + static inline std::shared_ptr filePermissionMock = nullptr; +}; + +class FilePermissionMock : public IFilePermissionMock { +public: + MOCK_METHOD2(PersistPermission, + int32_t(const vector &uriPolicies, deque &errorResults)); + MOCK_METHOD2(RevokePermission, int32_t(const vector &uriPolicies, + deque &errorResults)); + MOCK_METHOD2(ActivatePermission, int32_t(const vector &uriPolicies, + deque &errorResults)); + MOCK_METHOD2(DeactivatePermission, int32_t(const vector &uriPolicies, + deque &errorResults)); + MOCK_METHOD2(CheckPersistentPermission, int32_t(const vector &uriPolicies, + vector &errorResults)); +}; +} +} +#endif diff --git a/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp b/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp new file mode 100644 index 000000000..f46fb4243 --- /dev/null +++ b/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "file_permission_mock.h" + +namespace OHOS { +using namespace AppFileService; +int32_t FilePermission::PersistPermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->PersistPermission(uriPolicies, errorResults); +} + +int32_t FilePermission::RevokePermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->RevokePermission(uriPolicies, errorResults); +} + +int32_t FilePermission::ActivatePermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->ActivatePermission(uriPolicies, errorResults); +} +int32_t FilePermission::DeactivatePermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->DeactivatePermission(uriPolicies, errorResults); +} +int32_t FilePermission::CheckPersistentPermission(const vector &uriPolicies, vector &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->CheckPersistentPermission(uriPolicies, errorResults); +} +} \ No newline at end of file diff --git a/tests/mock/parameter_mock/include/parameter_mock.h b/tests/mock/parameter_mock/include/parameter_mock.h new file mode 100644 index 000000000..76136ae9a --- /dev/null +++ b/tests/mock/parameter_mock/include/parameter_mock.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MOCK_OHOS_MOCK_PARAMETER_H +#define MOCK_OHOS_MOCK_PARAMETER_H + +#include +#include + +namespace OHOS { +namespace AppFileService { +class IParamMoc { +public: + virtual ~IParamMoc() = default; +public: + virtual int GetParameter(const char *key, const char *def, char *value, uint32_t len) = 0; +public: + static inline std::shared_ptr paramMoc = nullptr; +}; + +class ParamMoc : public IParamMoc { +public: + MOCK_METHOD4(GetParameter, int(const char *key, const char *def, char *value, uint32_t len)); +}; +} +} +#endif \ No newline at end of file diff --git a/tests/mock/parameter_mock/src/parameter_mock.cpp b/tests/mock/parameter_mock/src/parameter_mock.cpp new file mode 100644 index 000000000..106ce53d8 --- /dev/null +++ b/tests/mock/parameter_mock/src/parameter_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "parameter_mock.h" + +#include "parameter.h" + +using namespace OHOS::AppFileService; +int GetParameter(const char *key, const char *def, char *value, uint32_t len) +{ + if (IParamMoc::paramMoc == nullptr) { + return -1; + } + return IParamMoc::paramMoc->GetParameter(key, def, value, len); +} \ No newline at end of file -- Gitee From 9989b54ac6d969e0d44605c696cdcdc5be8b3ef2 Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Wed, 7 Aug 2024 17:53:52 +0800 Subject: [PATCH 14/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: Ic8ab329925a8e0c08c4a11fc6ead6471c9f60266 --- test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp b/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp index 518a285cb..7344bf7cf 100644 --- a/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp +++ b/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp @@ -237,9 +237,6 @@ HWTEST_F(NDKFileUriTest, get_path_from_uri_test_007, TestSize.Level1) fileUriStr += "data/storage/el2/base/haps/entry/files/GetPathFromUri006.txt"; fileUriStr += "?networkid=64799ecdf70788e396f454ff4a6e6ae4b09e20227c39c21f6e67a2aacbcef7b9"; const char *fileUri = fileUriStr.c_str(); - std::string filePathUri = "/data/storage/el2/share/r/" + bundleB; - filePathUri += "/data/storage/el2/distributedfiles/.remote_share/"; - filePathUri += "data/storage/el2/base/haps/entry/files/GetPathFromUri006.txt"; char *result = nullptr; unsigned int length = fileUriStr.size(); FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(nullptr, length, &result); @@ -410,7 +407,7 @@ HWTEST_F(NDKFileUriTest, is_valid_uri_test_003, TestSize.Level1) bool flags = OH_FileUri_IsValidUri(nullptr, length); EXPECT_EQ(flags, false); - flags = OH_FileUri_IsValidUri(nullptr, length - 1); + flags = OH_FileUri_IsValidUri(fileUri, length - 1); EXPECT_EQ(flags, false); GTEST_LOG_(INFO) << "is_valid_uri_test_003"; } -- Gitee From 3667653ce4d66de22607be2a10accde89016247c Mon Sep 17 00:00:00 2001 From: chen0088 Date: Tue, 6 Aug 2024 16:06:41 +0800 Subject: [PATCH 15/53] add ut Signed-off-by: chen0088 --- tests/unittests/backup_tools/BUILD.gn | 2 +- .../tools_op_incremental_restore_test.cpp | 157 ------------------ 2 files changed, 1 insertion(+), 158 deletions(-) diff --git a/tests/unittests/backup_tools/BUILD.gn b/tests/unittests/backup_tools/BUILD.gn index b30de9358..ec2f582eb 100644 --- a/tests/unittests/backup_tools/BUILD.gn +++ b/tests/unittests/backup_tools/BUILD.gn @@ -84,8 +84,8 @@ ohos_unittest("backup_tool_restore_test") { "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_restore_mock.cpp", "${path_backup}/tools/backup_tool/src/tools_op.cpp", diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp index e72348a50..9d0847e42 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp @@ -628,161 +628,4 @@ HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_ } GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1101"; } - -/** - * @tc.number: SUB_backup_tools_op_incremental_restore_1200 - * @tc.name: SUB_backup_tools_op_incremental_restore_1200 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1200"; - try { - map> mapArgToVal; - mapArgToVal["depMode"] = {"false"}; - g_exec(mapArgToVal); - EXPECT_EQ(mapArgToVal["depMode"][0], "false"); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1200"; -} - -/** - * @tc.number: SUB_backup_tools_op_incremental_restore_1201 - * @tc.name: SUB_backup_tools_op_incremental_restore_1201 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1201, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1201"; - try { - map> mapArgToVal = { - {"pathCapFile", {"path"}}, - {"bundles", {"bundle1"}}, - {"incrementalTime", {"time"}} - }; - int ret = g_exec(mapArgToVal); - EXPECT_LT(ret, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1201"; -} - -/** - * @tc.number: SUB_backup_tools_op_incremental_restore_1202 - * @tc.name: SUB_backup_tools_op_incremental_restore_1202 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1202, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1202"; - try { - map> mapArgToVal = { - {"bundles", {"bundle1"}}, - {"incrementalTime", {"time"}} - }; - int ret = g_exec(mapArgToVal); - EXPECT_LT(ret, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1202"; -} - -/** - * @tc.number: SUB_backup_tools_op_incremental_restore_1203 - * @tc.name: SUB_backup_tools_op_incremental_restore_1203 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1203, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1203"; - try { - map> mapArgToVal = { - {"pathCapFile", {"path"}}, - {"bundles", {"bundle1"}}, - {"incrementalTime", {"time"}}, - {"depMode", {"true"}} - }; - int ret = g_exec(mapArgToVal); - EXPECT_LT(ret, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1203"; -} - -/** - * @tc.number: SUB_backup_tools_op_incremental_restore_1204 - * @tc.name: SUB_backup_tools_op_incremental_restore_1204 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1204, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1204"; - try { - map> mapArgToVal = { - {"pathCapFile", {"path"}}, - {"incrementalTime", {"time"}} - }; - int ret = g_exec(mapArgToVal); - EXPECT_LT(ret, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1204"; -} - -/** - * @tc.number: SUB_backup_tools_op_incremental_restore_1205 - * @tc.name: SUB_backup_tools_op_incremental_restore_1205 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1205, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1205"; - try { - map> mapArgToVal = { - {"pathCapFile", {"path"}}, - {"bundles", {"bundle1"}} - }; - int ret = g_exec(mapArgToVal); - EXPECT_LT(ret, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1205"; -} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From 1e1e4ca8e8228e88ce8897f363b1e31644e6b205 Mon Sep 17 00:00:00 2001 From: hunili Date: Thu, 8 Aug 2024 10:57:34 +0800 Subject: [PATCH 16/53] Rename err try to copy issue: https://gitee.com/openharmony/filemanagement_app_file_service/issues/IAINM6 Signed-off-by: hunili --- utils/src/b_filesystem/b_file.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/utils/src/b_filesystem/b_file.cpp b/utils/src/b_filesystem/b_file.cpp index 32e81090d..097125673 100644 --- a/utils/src/b_filesystem/b_file.cpp +++ b/utils/src/b_filesystem/b_file.cpp @@ -186,10 +186,19 @@ bool BFile::MoveFile(const string &from, const string &to) throw BError(errno); } newPath.append("/").append(basename(name.get())); - if (rename(oldPath.c_str(), newPath.c_str())) { - HILOGE("failed to rename path, oldPath: %{public}s, newPath: %{public}s, errno: %{public}d", - GetAnonyPath(oldPath).c_str(), GetAnonyPath(newPath).c_str(), errno); - throw BError(errno); + if (rename(oldPath.c_str(), newPath.c_str()) != 0) { + HILOGI("rename err,try copy errno: %{public}d", errno); + UniqueFd fdFrom(open(oldPath.data(), O_RDONLY)); + if (fdFrom == -1) { // -1: fd error code + HILOGE("failed to open the file %{public}s", GetAnonyPath(from).c_str()); + throw BError(errno); + } + UniqueFd fdTo(open(newPath.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); + if (fdTo == -1) { // -1: fd error code + HILOGE("failed to open the file %{public}s", GetAnonyPath(to).c_str()); + throw BError(errno); + } + SendFile(fdTo, fdFrom); } return true; } catch (const BError &e) { -- Gitee From ad1d46ca1b35b47ce637bbea7ea7d99db67c4453 Mon Sep 17 00:00:00 2001 From: "yaoruozi1@huawei.com" Date: Wed, 7 Aug 2024 17:10:53 +0800 Subject: [PATCH 17/53] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E5=88=86=E8=BA=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yaoruozi1@huawei.com --- .../include/module_external/bms_adapter.h | 4 + .../module_ipc/svc_backup_connection.h | 8 +- .../src/module_external/bms_adapter.cpp | 81 ++++++++++++------- services/backup_sa/src/module_ipc/service.cpp | 44 ++++++---- .../src/module_ipc/svc_backup_connection.cpp | 7 +- .../module_ipc/svc_restore_deps_manager.cpp | 9 ++- .../src/module_ipc/svc_session_manager.cpp | 2 +- .../mock/module_external/bms_adapter_mock.cpp | 9 ++- .../module_ipc/svc_session_manager_mock.cpp | 5 +- .../module_ipc/svc_backup_connection_test.cpp | 2 +- .../module_ipc/svc_session_manager_test.cpp | 4 +- .../b_jsonutil/b_jsonutil_test.cpp | 6 +- utils/include/b_json/b_json_entity_caps.h | 8 +- utils/include/b_jsonutil/b_jsonutil.h | 13 ++- utils/include/b_resources/b_constants.h | 1 + utils/src/b_jsonutil/b_jsonutil.cpp | 20 +++-- utils/src/b_ohos/startup/backup_para.cpp | 2 - 17 files changed, 152 insertions(+), 73 deletions(-) diff --git a/services/backup_sa/include/module_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h index 5f106294c..e56ec31dd 100644 --- a/services/backup_sa/include/module_external/bms_adapter.h +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -63,6 +63,10 @@ public: static std::vector GetBundleInfosForSA(); static void GetBundleInfoForSA(std::string bundleName, std::vector &bundleInfos); +private: + static bool GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installedBundle, const std::string &bundleName, + std::vector &extensionInfos, sptr bms, + int32_t userId); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_BUNDLE_MGR_ADAPTER_H diff --git a/services/backup_sa/include/module_ipc/svc_backup_connection.h b/services/backup_sa/include/module_ipc/svc_backup_connection.h index a8c46591c..1958fcb8c 100644 --- a/services/backup_sa/include/module_ipc/svc_backup_connection.h +++ b/services/backup_sa/include/module_ipc/svc_backup_connection.h @@ -76,7 +76,7 @@ public: * @param callConnected */ void SetCallback(std::function callConnected); - + /** * @brief Set the CallDied object * @@ -91,8 +91,9 @@ public: public: SvcBackupConnection(std::function callDied, - std::function callConnected) - : callDied_(callDied), callConnected_(callConnected) + std::function callConnected, + std::string bundleNameIndexInfo) + : callDied_(callDied), callConnected_(callConnected), bundleNameIndexInfo_(bundleNameIndexInfo) { } ~SvcBackupConnection() override {}; @@ -108,6 +109,7 @@ private: std::function callDied_; std::function callConnected_; + std::string bundleNameIndexInfo_; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index 87b1cfda4..09a0d132a 100644 --- a/services/backup_sa/src/module_external/bms_adapter.cpp +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -22,6 +22,7 @@ #include "b_error/b_error.h" #include "b_file_info.h" +#include "b_jsonutil/b_jsonutil.h" #include "b_json/b_json_entity_extension_config.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" @@ -47,7 +48,6 @@ const string LINUX_HAP_CODE_PATH = "2"; const string MEDIA_LIBRARY_HAP = "com.ohos.medialibrary.medialibrarydata"; const string EXTERNAL_FILE_HAP = "com.ohos.UserFile.ExternalFileManager"; const int E_ERR = -1; -const int SINGLE_BUNDLE_NUM = 1; const vector dataDir = {"app", "local", "distributed", "database", "cache"}; } // namespace @@ -95,7 +95,8 @@ static int64_t GetBundleStats(const string &bundleName, int32_t userId) } auto bms = GetBundleManager(); vector bundleStats; - bool res = bms->GetBundleStats(bundleName, userId, bundleStats); + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + bool res = bms->GetBundleStats(bundleDetailInfo.bundleName, userId, bundleStats, bundleDetailInfo.bundleIndex); if (!res || bundleStats.size() != dataDir.size()) { HILOGE("An error occurred in querying bundle stats. name:%{public}s", bundleName.c_str()); return 0; @@ -122,25 +123,20 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto continue; } AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { - if (bundleNames.size() != SINGLE_BUNDLE_NUM) { - HILOGE("bundleName:%{public}s, current bundle info for backup/restore is empty", bundleName.c_str()); - continue; - } - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Failed to get bundle info"); - } - if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || - installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { - HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); + std::vector extensionInfos; + bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + if (!getBundleSuccess) { + HILOGE("Get current extension failed"); continue; } auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = - GetAllowAndExtName(installedBundle.extensionInfos); + GetAllowAndExtName(extensionInfos); int64_t dataSize = 0; if (allToBackup) { dataSize = GetBundleStats(installedBundle.name, userId); } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, dataSize, 0, allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo}); @@ -258,6 +254,7 @@ static bool GenerateBundleStatsIncrease(int32_t userId, const vector &bu std::string curBundleName = bundleInfos[i].name; HILOGD("BundleMgrAdapter name for %{public}s", curBundleName.c_str()); BJsonEntityCaps::BundleInfo newBundleInfo = {.name = curBundleName, + .appIndex = bundleInfos[i].appIndex, .versionCode = bundleInfos[i].versionCode, .versionName = bundleInfos[i].versionName, .spaceOccupied = pkgFileSizes[i], @@ -284,16 +281,14 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement auto bundleName = bundleNameTime.bundleName; HILOGD("Begin get bundleName:%{private}s", bundleName.c_str()); AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle info"); - } - if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || - installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { - HILOGI("Unsupported applications, name : %{private}s", installedBundle.name.data()); + std::vector extensionInfos; + bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + if (!getBundleSuccess) { + HILOGE("Failed to get bundle info from bms, bundleName:%{public}s", bundleName.c_str()); continue; } struct BJsonEntityCaps::BundleBackupConfigPara backupPara; - if (!GetBackupExtConfig(installedBundle.extensionInfos, backupPara)) { + if (!GetBackupExtConfig(extensionInfos, backupPara)) { HILOGE("No backup extension ability found"); continue; } @@ -301,7 +296,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement backupPara.excludes)) { continue; } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, 0, 0, backupPara.allToBackup, backupPara.fullBackupOnly, backupPara.extensionName, @@ -342,9 +338,9 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = GetAllowAndExtName(installedBundle.extensionInfos); if (!allToBackup) { - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, - installedBundle.versionName, 0, 0, allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, - extraInfo}); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, 0, 0, allToBackup, fullBackupOnly, extName, + restoreDeps, supportScene, extraInfo}); continue; } auto it = std::find_if(extraIncreData.begin(), extraIncreData.end(), @@ -405,7 +401,7 @@ std::vector BundleMgrAdapter::GetBundleInfosForSA() int32_t ret = samgrProxy->GetExtensionSaIds(BConstants::EXTENSION_BACKUP, saIds); HILOGI("GetExtensionSaIds ret: %{public}d", ret); for (auto saId : saIds) { - saBundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {std::to_string(saId), 0, "", 0, 0, true, false, + saBundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {std::to_string(saId), 0, 0, "", 0, 0, true, false, "", "", "", ""}); } return saBundleInfos; @@ -435,7 +431,38 @@ void BundleMgrAdapter::GetBundleInfoForSA(std::string bundleName, std::vector &extensionInfos, + sptr bms, int32_t userId) +{ + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + int32_t flags = static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) | + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) | + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA); + ErrCode ret = bms->GetCloneBundleInfo(bundleDetailInfo.bundleName, flags, bundleDetailInfo.bundleIndex, + installedBundle, userId); + if (ret != ERR_OK) { + HILOGE("bundleName:%{public}s, ret:%{public}d, current bundle info for backup/restore is empty", + bundleName.c_str(), ret); + return false; + } + if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || + installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { + HILOGE("Unsupported applications, name : %{public}s", installedBundle.name.data()); + return false; + } + HILOGI("bundleName:%{public}s, hapMoudleInfos size:%{public}zu", bundleName.c_str(), + installedBundle.hapModuleInfos.size()); + std::vector hapModuleInfos = installedBundle.hapModuleInfos; + for (auto &hapModuleInfo : hapModuleInfos) { + extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(), + hapModuleInfo.extensionInfos.end()); + } + HILOGI("bundleName:%{public}s, extensionInfos size:%{public}zu", bundleName.c_str(), extensionInfos.size()); + return true; +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index a896ceb52..dc7b90a9f 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -202,8 +202,10 @@ string Service::VerifyCallerAndGetCallerName() if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) { throw BError(BError::Codes::SA_INVAL_ARG, "Get hap token info failed"); } - session_->VerifyBundleName(hapTokenInfo.bundleName); - return hapTokenInfo.bundleName; + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(hapTokenInfo.bundleName, + hapTokenInfo.instIndex); + session_->VerifyBundleName(bundleNameIndexInfo); + return bundleNameIndexInfo; } else { string str = to_string(tokenCaller); HILOGE("tokenID = %{private}s", GetAnonyString(str).c_str()); @@ -338,6 +340,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, for (auto &restoreInfo : restoreInfos) { if (SAUtils::IsSABundleName(restoreInfo.name)) { BJsonEntityCaps::BundleInfo info = {.name = restoreInfo.name, + .appIndex = restoreInfo.appIndex, .versionCode = restoreInfo.versionCode, .versionName = restoreInfo.versionName, .spaceOccupied = restoreInfo.spaceOccupied, @@ -355,6 +358,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, continue; } BJsonEntityCaps::BundleInfo info = {.name = (*it).name, + .appIndex = (*it).appIndex, .versionCode = (*it).versionCode, .versionName = (*it).versionName, .spaceOccupied = (*it).spaceOccupied, @@ -372,7 +376,8 @@ static void HandleExceptionOnAppendBundles(sptr session, const vector &appendBundleNames, const vector &restoreBundleNames) { if (appendBundleNames.size() != restoreBundleNames.size()) { - HILOGE("AppendBundleNames not equal restoreBundleNames."); + HILOGE("AppendBundleNames not equal restoreBundleNames, appendBundleNames size:%{public}zu," + "restoreBundleNames size:%{public}zu", appendBundleNames.size(), restoreBundleNames.size()); for (auto bundleName : appendBundleNames) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), [&bundleName](const auto &obj) { return obj == bundleName; }); @@ -398,7 +403,7 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector bundleNamesOnly; std::map> bundleNameDetailMap = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); - auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNamesOnly); + auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); if (restoreBundleNames.empty()) { @@ -497,37 +502,42 @@ void Service::SetCurrentSessProperties(std::vector HILOGI("Start"); for (auto restoreInfo : restoreBundleInfos) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), - [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); + [&restoreInfo](const auto &bundleName) { + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, + restoreInfo.appIndex); + return bundleName == bundleNameIndexInfo; + }); if (it == restoreBundleNames.end()) { throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); } HILOGD("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), restoreInfo.extensionName.c_str()); + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex); if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); - session_->RemoveExtInfo(restoreInfo.name); + session_->RemoveExtInfo(bundleNameIndexInfo); continue; } - session_->SetBundleRestoreType(restoreInfo.name, restoreType); - session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); - session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); - session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); - session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); + session_->SetBundleRestoreType(bundleNameIndexInfo, restoreType); + session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode); + session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName); + session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied); + session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName); BJsonUtil::BundleDetailInfo broadCastInfo; BJsonUtil::BundleDetailInfo uniCastInfo; - bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, restoreInfo.name, BROADCAST_TYPE, + bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE, broadCastInfo); if (broadCastRet) { bool notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail(broadCastInfo); HILOGI("Publish event end, notify result is:%{public}d", notifyRet); } - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, restoreInfo.name, UNICAST_TYPE, + bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, UNICAST_TYPE, uniCastInfo); if (uniCastRet) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); - session_->SetBackupExtInfo(restoreInfo.name, uniCastInfo.detail); + session_->SetBackupExtInfo(bundleNameIndexInfo, uniCastInfo.detail); } } HILOGI("End"); @@ -822,21 +832,23 @@ void Service::NotifyCloneBundleFinish(std::string bundleName) void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action) { + BJsonUtil::BundleDetailInfo bundleDetail = BJsonUtil::ParseBundleNameIndexStr(bundleName); string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */ - HILOGD("BackupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); + HILOGI("BackupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */ RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */ string bundleExtInfo = session_->GetBackupExtInfo(bundleName); HILOGI("BundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str()); - want.SetElementName(bundleName, backupExtName); + want.SetElementName(bundleDetail.bundleName, backupExtName); want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast(restoreType)); want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName); want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo); want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); + want.SetParam(BConstants::EXTENSION_APP_CLONE_INDEX_PARA, bundleDetail.bundleIndex); } ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) diff --git a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp index befce1a26..f9dc891c6 100644 --- a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp +++ b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp @@ -63,7 +63,12 @@ void SvcBackupConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &el "PID", getpid(), "TIME", strTime.str() ); - callConnected_(move(bundleName)); + if (bundleNameIndexInfo_.find(bundleName) == string::npos) { + HILOGE("Current bundle name is wrong, bundleNameIndexInfo:%{public}s, bundleName:%{public}s", + bundleNameIndexInfo_.c_str(), bundleName.c_str()); + return; + } + callConnected_(move(bundleNameIndexInfo_)); HILOGI("called end"); } diff --git a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp index 94bb23b36..5907c0ecc 100644 --- a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp @@ -15,6 +15,7 @@ #include "module_ipc/svc_restore_deps_manager.h" +#include "b_jsonutil/b_jsonutil.h" #include "filemgmt_libhilog.h" namespace OHOS::FileManagement::Backup { @@ -30,9 +31,10 @@ vector SvcRestoreDepsManager::GetRestoreBundleNames(const vector &bundleInfos) { for (auto &bundleInfo : bundleInfos) { - if (depsMap_.find(bundleInfo.name) != depsMap_.end()) { + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(bundleInfo.name, bundleInfo.appIndex); + if (depsMap_.find(bundleNameIndexInfo) != depsMap_.end()) { continue; } allBundles_.emplace_back(bundleInfo); @@ -92,7 +95,7 @@ void SvcRestoreDepsManager::BuildDepsMap(const vector SvcSessionManager::GetBackupAbilityExt(const string &b revPtrStrong->ExtConnectDone(move(bundleName)); }; - return sptr(new SvcBackupConnection(callDied, callConnected)); + return sptr(new SvcBackupConnection(callDied, callConnected, bundleName)); } std::shared_ptr SvcSessionManager::GetBackupSAExt(const std::string &bundleName) diff --git a/tests/mock/module_external/bms_adapter_mock.cpp b/tests/mock/module_external/bms_adapter_mock.cpp index cef59d5f1..fd6b866a6 100644 --- a/tests/mock/module_external/bms_adapter_mock.cpp +++ b/tests/mock/module_external/bms_adapter_mock.cpp @@ -32,7 +32,8 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } @@ -46,7 +47,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } @@ -55,7 +57,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 528e46728..eff1d65e0 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -104,7 +104,8 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & if (!it->second.backUpConnection) { auto callDied = [](const string &&bundleName) {}; auto callConnected = [](const string &&bundleName) {}; - it->second.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected)); + it->second.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, + bundleName)); sptr mock = sptr(new BackupExtExtensionMock()); it->second.backUpConnection->OnAbilityConnectDone({}, mock->AsObject(), 0); } @@ -114,7 +115,7 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & sptr SvcSessionManager::GetBackupAbilityExt(const string &bundleName) { GTEST_LOG_(INFO) << "GetBackupAbilityExt"; - return sptr(new SvcBackupConnection(nullptr, nullptr)); + return sptr(new SvcBackupConnection(nullptr, nullptr, bundleName)); } void SvcSessionManager::DumpInfo(const int fd, const std::vector &args) diff --git a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp index cfdfacc4c..772053763 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp @@ -53,7 +53,7 @@ static void CallDone(const std::string &&name) void SvcBackupConnectionTest::SetUpTestCase() { - backupCon_ = sptr(new SvcBackupConnection(CallDied, CallDone)); + backupCon_ = sptr(new SvcBackupConnection(CallDied, CallDone, "com.example.app")); castMock = std::make_shared(); IfaceCastMock::cast = castMock; } diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp index a60ac156d..d50fa18b8 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp @@ -668,7 +668,7 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtConnection_0100, tes } BackupExtInfo info; - info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr)); + info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; auto ret = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); @@ -1764,7 +1764,7 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_ClearSessionData_0100, tes BackupExtInfo info; info.timerStatus = true; info.schedAction = BConstants::ServiceSchedAction::RUNNING; - info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr)); + info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); EXPECT_TRUE(sessionManagerPtr_ != nullptr); sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; diff --git a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp index 4cb7c1f98..5ea1cfec4 100644 --- a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp +++ b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp @@ -52,8 +52,7 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_ParseBundleNameIndexStr_0100, testing::ext::T GTEST_LOG_(INFO) << "BJsonUtilTest-begin b_dir_GetDirFiles_0100"; try { std::string bundleName = "com.hos.app01:1"; - std::string pattern = ":"; - BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName, pattern); + BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); EXPECT_EQ("com.hos.app01", detailInfo.bundleName); } catch (...) { EXPECT_TRUE(false); @@ -76,8 +75,7 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_ParseBundleNameIndexStr_0200, testing::ext::T GTEST_LOG_(INFO) << "BJsonUtilTest-begin ParseBundleNameIndexStr_0200"; try { std::string bundleName = "com.hos.app01"; - std::string pattern = ":"; - BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName, pattern); + BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); EXPECT_EQ("com.hos.app01", detailInfo.bundleName); } catch (...) { EXPECT_TRUE(false); diff --git a/utils/include/b_json/b_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h index 30c38e667..e641077e0 100644 --- a/utils/include/b_json/b_json_entity_caps.h +++ b/utils/include/b_json/b_json_entity_caps.h @@ -24,6 +24,7 @@ class BJsonEntityCaps : public BJsonEntity { public: struct BundleInfo { std::string name; + int appIndex; int64_t versionCode; std::string versionName; int64_t spaceOccupied; @@ -74,6 +75,7 @@ public: for (const auto &item : bundleInfos) { Json::Value arrObj; arrObj["name"] = item.name; + arrObj["appIndex"] = item.appIndex; arrObj["versionCode"] = item.versionCode; arrObj["versionName"] = item.versionName; arrObj["spaceOccupied"] = item.spaceOccupied; @@ -210,7 +212,11 @@ public: if (item.isMember("fullBackupOnly") && item["fullBackupOnly"].isBool()) { fullBackupOnly = item["fullBackupOnly"].asBool(); } - bundleInfos.emplace_back(BundleInfo {item["name"].asString(), item["versionCode"].asInt64(), + int appIndex = 0; + if (item.isMember("appIndex") && item["appIndex"].isInt()) { + appIndex = item["appIndex"].asInt(); + } + bundleInfos.emplace_back(BundleInfo {item["name"].asString(), appIndex, item["versionCode"].asInt64(), item["versionName"].asString(), item["spaceOccupied"].asInt64(), increSpaceOccupied, item["allToBackup"].asBool(), fullBackupOnly, diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index 9efa19376..8799488df 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -34,11 +34,10 @@ public: * @brief 带有拼接字符的bundleName按照拼接字符进行分割 * * @param bundleNameStr bundleName拼接index的字符串 - * @param patternInfo 拼接字符串 * * @return 分割好的结果赋值给结构体 */ - static BundleDetailInfo ParseBundleNameIndexStr (const std::string &bundleNameStr, const std::string &patternInfo); + static BundleDetailInfo ParseBundleNameIndexStr (const std::string &bundleNameStr); /** * @brief 将传进来的bundleNames的集合进行按照拼接字符分割处理 @@ -94,6 +93,16 @@ public: * */ static bool BuildRestoreErrInfo(std::string &jsonStr, int errCode, std::string errMsg); + + /** + * @brief 拼接包名和分身对应的索引 + * + * @param bundleName 包名 + * @param bundleIndex 索引 + * + * @return 拼接结果 + */ + static std::string BuildBundleNameIndexInfo(const std::string &bundleName, int bundleIndex); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index 512526b5c..7d85e5f90 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -30,6 +30,7 @@ static inline const char *EXTENSION_VERSION_CODE_PARA = "versionCode"; static inline const char *EXTENSION_VERSION_NAME_PARA = "versionName"; static inline const char *EXTENSION_RESTORE_EXT_INFO_PARA = "restoreExtInfo"; static inline const char *EXTENSION_BACKUP_EXT_INFO_PARA = "backupExtInfo"; +static inline const char *EXTENSION_APP_CLONE_INDEX_PARA = "ohos.extra.param.key.appCloneIndex"; enum class ExtensionAction { INVALID = 0, diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index 578be2fd8..53fdb36e8 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -28,11 +28,10 @@ namespace { const static std::string BUNDLE_INDEX_SPLICE = ":"; } -BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string &bundleNameStr, - const std::string &patternInfo) +BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string &bundleNameStr) { HILOGI("Start parse bundle name and index"); - size_t hasPos = bundleNameStr.find(patternInfo); + size_t hasPos = bundleNameStr.find(BUNDLE_INDEX_SPLICE); BundleDetailInfo bundleDetailInfo; if (hasPos == std::string::npos) { bundleDetailInfo.bundleName = bundleNameStr; @@ -74,7 +73,7 @@ std::map> BJsonUtil::Build bundleNamesOnly.emplace_back(bundleName); } else { std::string bundleNameSplit = bundleName.substr(0, pos); - std::string indexSplit = bundleName.substr(pos, bundleName.size() - 1); + std::string indexSplit = bundleName.substr(pos + 1); int index = std::stoi(indexSplit); bundleNameOnly = bundleNameSplit; bundleIndex = index; @@ -82,7 +81,7 @@ std::map> BJsonUtil::Build } std::string bundleInfo = bundleInfos[i]; ParseBundleInfoJson(bundleInfo, bundleDetailInfos, bundleNameOnly, bundleIndex, userId); - bundleNameDetailMap[bundleNameOnly] = bundleDetailInfos; + bundleNameDetailMap[bundleName] = bundleDetailInfos; } HILOGI("End BuildBundleInfos"); return bundleNameDetailMap; @@ -180,4 +179,15 @@ bool BJsonUtil::BuildRestoreErrInfo(std::string &jsonStr, int errCode, std::stri cJSON_free(data); return true; } + +std::string BJsonUtil::BuildBundleNameIndexInfo(const std::string &bundleName, int appIndex) +{ + std::string result = bundleName; + if (appIndex == BUNDLE_INDEX_DEFAULT_VAL) { + return result; + } + result += BUNDLE_INDEX_SPLICE; + result += std::to_string(appIndex); + return result; +} } \ No newline at end of file diff --git a/utils/src/b_ohos/startup/backup_para.cpp b/utils/src/b_ohos/startup/backup_para.cpp index c5f9c1d9d..46754c5dc 100644 --- a/utils/src/b_ohos/startup/backup_para.cpp +++ b/utils/src/b_ohos/startup/backup_para.cpp @@ -38,7 +38,6 @@ using namespace std; static tuple GetConfigParameterValue(const string &key, uint32_t len) { int handle = static_cast(FindParameter(key.c_str())); - HILOGI("start get config param value."); if (handle == -1) { HILOGI("Fail to find parameter."); return {false, ""}; @@ -50,7 +49,6 @@ static tuple GetConfigParameterValue(const string &key, uint32_t l HILOGI("Fail to get parameter value."); return {false, ""}; } - HILOGI("end get config param value."); return {true, buffer.get()}; } catch (const bad_alloc &e) { HILOGE("Fail to get parameter value: %{public}s.", e.what()); -- Gitee From 8efbc7a4365cdbf425d20b7c07b0a36a3a2f9532 Mon Sep 17 00:00:00 2001 From: chen0088 Date: Thu, 8 Aug 2024 15:30:55 +0800 Subject: [PATCH 18/53] add ut Signed-off-by: chen0088 --- .../backup_utils/b_error/b_error_test.cpp | 56 +++- .../b_jsonutil/b_jsonutil_test.cpp | 275 +++++++++++++++++- 2 files changed, 314 insertions(+), 17 deletions(-) diff --git a/tests/unittests/backup_utils/b_error/b_error_test.cpp b/tests/unittests/backup_utils/b_error/b_error_test.cpp index d48c401d7..027edb739 100644 --- a/tests/unittests/backup_utils/b_error/b_error_test.cpp +++ b/tests/unittests/backup_utils/b_error/b_error_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -452,4 +452,58 @@ HWTEST_F(BErrorTest, b_error_int_0100, testing::ext::TestSize.Level0) EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "BErrorTest-end b_error_int_0100"; } + +/** + * @tc.number: SUB_backup_b_error_GetCodeByErrno_0100 + * @tc.name: b_error_GetCodeByErrno_0100 + * @tc.desc: Test function of int interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BErrorTest, b_error_GetCodeByErrno_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCodeByErrno_0100"; + int32_t errnoSys = 0; + int result = BError::GetCodeByErrno(errnoSys); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCodeByErrno_0100"; +} + +/** + * @tc.number: SUB_backup_b_error_GetCodeByErrno_0200 + * @tc.name: b_error_GetCodeByErrno_0200 + * @tc.desc: Test function of int interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BErrorTest, b_error_GetCodeByErrno_0200, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCodeByErrno_0200"; + int32_t errnoSys = EPERM; + int result = BError::GetCodeByErrno(errnoSys); + EXPECT_EQ(result, BError::BackupErrorCode::E_IPCSS); + GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCodeByErrno_0200"; +} + +/** + * @tc.number: SUB_backup_b_error_GetCodeByErrno_0300 + * @tc.name: b_error_GetCodeByErrno_0300 + * @tc.desc: Test function of int interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BErrorTest, b_error_GetCodeByErrno_0300, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCodeByErrno_0300"; + int32_t errnoSys = -EPERM; + int result = BError::GetCodeByErrno(errnoSys); + EXPECT_EQ(result, BError::BackupErrorCode::E_UKERR); + GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCodeByErrno_0300"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp index 4cb7c1f98..d05fd40e7 100644 --- a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp +++ b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp @@ -30,6 +30,10 @@ namespace OHOS::FileManagement::Backup { using namespace std; +namespace { +constexpr uint32_t TEST_USER_ID = 100; +} // namespace + class BJsonUtilTest : public testing::Test { public: static void SetUpTestCase(void) {}; @@ -107,7 +111,7 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0100, testing::ext::TestSize std::string bundleInfo2 = "info2"; bundleInfos.push_back(bundleInfo); bundleInfos.push_back(bundleInfo2); - int32_t userId = 100; + int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); EXPECT_TRUE(result.empty()); @@ -135,9 +139,9 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0200, testing::ext::TestSize std::string bundleName = "bundle"; bundleNames.push_back(bundleName); std::vector bundleInfos; - std::string bundleInfo = "info1"; + std::string bundleInfo = "{\"infos\":\"infos\"}"; bundleInfos.push_back(bundleInfo); - int32_t userId = 100; + int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); EXPECT_FALSE(result.empty()); @@ -162,24 +166,15 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0300, testing::ext::TestSize GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0300"; try { std::vector bundleNames; - std::string bundleName = "bundle1"; - std::string bundleName2 = "bundle2"; - std::string bundleName3 = "bundle3"; + std::string bundleName = "bundle1:"; bundleNames.push_back(bundleName); - bundleNames.push_back(bundleName2); - bundleNames.push_back(bundleName3); std::vector bundleInfos; std::string bundleInfo = "info1"; - std::string bundleInfo2 = "info2"; - std::string bundleInfo3 = "info3"; bundleInfos.push_back(bundleInfo); - bundleInfos.push_back(bundleInfo2); - bundleInfos.push_back(bundleInfo3); - int32_t userId = 100; + int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; - int32_t size = 3; auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); - EXPECT_EQ(bundleNamesOnly.size(), size); + EXPECT_TRUE(result.empty()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; @@ -187,6 +182,36 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0300, testing::ext::TestSize GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0300"; } +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0301 + * @tc.name: b_jsonutil_BuildBundleInfos_0301 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0301, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0301"; + try { + std::vector bundleNames; + std::string bundleName = ":bundle1"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = "info1"; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_TRUE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0301"; +} + /** * @tc.number: b_jsonutil_BuildBundleInfos_0400 * @tc.name: b_jsonutil_BuildBundleInfos_0400 @@ -206,7 +231,7 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0400, testing::ext::TestSize std::vector bundleInfos; std::string bundleInfo = {"{\"infos\":[{\"type\":\"type1\",\"details\":\"details1\"}]}"}; bundleInfos.push_back(bundleInfo); - int32_t userId = 100; + int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); @@ -218,6 +243,192 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0400, testing::ext::TestSize GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0400"; } +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0500 + * @tc.name: b_jsonutil_BuildBundleInfos_0500 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0500, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0500"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":null}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0500"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0600 + * @tc.name: b_jsonutil_BuildBundleInfos_0600 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0600, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0600"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":123}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0600"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0700 + * @tc.name: b_jsonutil_BuildBundleInfos_0700 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0700, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0700"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":\"testType\",\"details\":null}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0700"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0800 + * @tc.name: b_jsonutil_BuildBundleInfos_0800 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0800, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0800"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":\"testType\",\"details\":[]}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0800"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0900 + * @tc.name: b_jsonutil_BuildBundleInfos_0900 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0900, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0900"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":\"testType\",\"details\":[\"detail\"]}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0900"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_1000 + * @tc.name: b_jsonutil_BuildBundleInfos_1000 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_1000, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_1000"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[\"infos\"]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_1000"; +} + /** * @tc.number: b_jsonutil_FindBundleInfoByName_0100 * @tc.name: b_jsonutil_FindBundleInfoByName_0100 @@ -277,6 +488,38 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_FindBundleInfoByName_0200, testing::ext::Test GTEST_LOG_(INFO) << "BJsonUtilTest-end FindBundleInfoByName_0200"; } +/** + * @tc.number: b_jsonutil_FindBundleInfoByName_0300 + * @tc.name: b_jsonutil_FindBundleInfoByName_0300 + * @tc.desc: Test function of FindBundleInfoByName interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_FindBundleInfoByName_0300, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin FindBundleInfoByName_0300"; + try { + std::map> bundleNameDetailsMap; + std::string bundleName = "bundle1"; + std::string jobType = "type"; + std::string jobType1 = "type1"; + BJsonUtil::BundleDetailInfo detailInfo; + detailInfo.bundleName = bundleName; + detailInfo.type = jobType; + bundleNameDetailsMap[bundleName] = {detailInfo}; + BJsonUtil::BundleDetailInfo bundleDetail; + + bool result = BJsonUtil::FindBundleInfoByName(bundleNameDetailsMap, bundleName, jobType1, bundleDetail); + EXPECT_EQ(false, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end FindBundleInfoByName_0300"; +} + /** * @tc.number: b_jsonutil_BuildRestoreErrInfo_0100 * @tc.name: b_jsonutil_BuildRestoreErrInfo_0100 -- Gitee From 5d61921dd01f16f20d06eda21c963b917aae335a Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Thu, 8 Aug 2024 16:35:26 +0800 Subject: [PATCH 19/53] add afs new testcase Signed-off-by: lvyuanyuan Change-Id: I195e2099033f010d4cd7a7ae49f9a238bc12d677 --- test/unittest/file_share_ndk_test/BUILD.gn | 1 + .../file_share_permission_sup_test/BUILD.gn | 61 +++++ .../file_share_permission_sup_test.cpp | 258 ++++++++++++++++++ .../remote_file_share_test.cpp | 138 ++++++++++ 4 files changed, 458 insertions(+) create mode 100644 test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn create mode 100644 test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp diff --git a/test/unittest/file_share_ndk_test/BUILD.gn b/test/unittest/file_share_ndk_test/BUILD.gn index 75128bd0b..8aa1a6eec 100644 --- a/test/unittest/file_share_ndk_test/BUILD.gn +++ b/test/unittest/file_share_ndk_test/BUILD.gn @@ -17,6 +17,7 @@ group("unittest") { testonly = true deps = [ "file_share_nopermission_test:file_share_no_permission_ndk_test", + "file_share_permission_sup_test:file_share_permission_ndk_sup_test", "file_share_permission_test:file_share_permission_ndk_test", ] } diff --git a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn new file mode 100644 index 000000000..e9c47a862 --- /dev/null +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") + +ohos_unittest("file_share_permission_ndk_sup_test") { + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${app_file_service_path}/cfi_blocklist.txt" + } + + module_out_path = "filemanagement/app_file_service" + include_dirs = [ + "include", + "${app_file_service_path}/interfaces/kits/ndk/fileshare/include", + "${app_file_service_path}/tests/mock/file_permission_native_mock/include", + "${app_file_service_path}/tests/mock/parameter_mock/include", + "//third_party/googletest/include", + ] + resource_config_file = "../../resource/ohos_test.xml" + sources = [ + "${app_file_service_path}/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp", + "${app_file_service_path}/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp", + "${app_file_service_path}/tests/mock/parameter_mock/src/parameter_mock.cpp", + "file_share_permission_sup_test.cpp", + ] + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + deps = [ + "${app_file_service_path}/interfaces/innerkits/native:fileshare_native", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] +} diff --git a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp new file mode 100644 index 000000000..25b889cef --- /dev/null +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "oh_file_share.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "permission_def.h" +#include "permission_state_full.h" +#include "securec.h" +#include "token_setproc.h" +#include "uri.h" + +#include "error_code.h" +#include "file_permission_mock.h" +#include "parameter_mock.h" + +using namespace testing::ext; +using namespace testing; +using namespace OHOS::AppFileService; +using namespace OHOS::Security::AccessToken; + +namespace OHOS::AppFileService::ModuleFileSharePermission { +void GrantNativePermission() +{ + const char **perms = new const char *[1]; + perms[0] = "ohos.permission.FILE_ACCESS_PERSIST"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "app_file_service", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +class NDKFileSharePermissionSupTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() {}; + void TearDown() {}; + static inline shared_ptr paramMoc_ = nullptr; + static inline shared_ptr filePermMoc_ = nullptr; +}; + +void NDKFileSharePermissionSupTest::SetUpTestCase() +{ + GrantNativePermission(); + paramMoc_ = make_shared(); + ParamMoc::paramMoc = paramMoc_; + + filePermMoc_ = make_shared(); + FilePermissionMock::filePermissionMock = filePermMoc_; +} + +void NDKFileSharePermissionSupTest::TearDownTestCase() +{ + ParamMoc::paramMoc = nullptr; + paramMoc_ = nullptr; + + FilePermissionMock::filePermissionMock = nullptr; + filePermMoc_ = nullptr; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_001 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_001 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/el2/base/PersistPermission.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(-1)); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(1)); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_001 end"; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_002 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_002 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = nullptr, + .length = 0, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ + memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + })), Return(1))); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + policies[0].uri = policyUriChar; + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ + memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + })), Return(1))); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + policies[0].length = sizeof(policyUriChar); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ + memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + })), Return(1))); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_002 end"; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_003 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ + memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)).WillOnce(Return(E_PERMISSION)); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + std::deque errorResults; + for (int i = 0; i <= MAX_ARRAY_SIZE; i++) { + PolicyErrorResult rlt; + errorResults.push_back(rlt); + } + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ + memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_PARAMS))); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 end"; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_004 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_004, TestSize.Level1) +{ + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + PolicyErrorResult rltOne = {.uri = string(policy.uri)}; + std::deque errorResults; + errorResults.push_back(rltOne); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ + memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(EPERM))); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_EPERM); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ + memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_DEVICE_NOT_SUPPORT))); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_UNKNOWN_ERROR); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_004 end"; +} +} // namespace OHOS::AppFileService::ModuleFileSharePermission diff --git a/test/unittest/remote_file_share/remote_file_share_test.cpp b/test/unittest/remote_file_share/remote_file_share_test.cpp index 5559074ba..6d49e0d1d 100644 --- a/test/unittest/remote_file_share/remote_file_share_test.cpp +++ b/test/unittest/remote_file_share/remote_file_share_test.cpp @@ -396,6 +396,74 @@ namespace { GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0011"; } + /** + * @tc.name: Remote_file_share_GetDfsUriFromLocal_0012 + * @tc.desc: Test function of GetDfsUriFromLocal() interface for FAILURE. + * the file name is chinese which has been encoded + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_GetDfsUriFromLocal_0012, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_GetDfsUriFromLocal_0012"; + string uriStr = "datashare://media/Photo/12/IMG_12345_0011/test.jpg"; + const int userId = 100; + + HmdfsUriInfo hui; + auto ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_EQ(ret, -EINVAL); + + uriStr = "datashare://media/Photo/12/IMG_12345_0011/test.jpg/others"; + ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_EQ(ret, -EINVAL); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0012"; + } + + /** + * @tc.name: Remote_file_share_GetDfsUriFromLocal_0013 + * @tc.desc: Test function of GetDfsUriFromLocal() interface for SUCCESS. + * the file name is chinese which has been encoded + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_GetDfsUriFromLocal_0013, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_GetDfsUriFromLocal_0013"; + const string uriStr = "file://media/Photo/12/IMG_12345_0011/test.jpg"; + const int userId = 100; + + HmdfsUriInfo hui; + auto ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_EQ(ret, 2); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0013"; + } + + /** + * @tc.name: Remote_file_share_GetDfsUriFromLocal_0014 + * @tc.desc: Test function of GetDfsUriFromLocal() interface for SUCCESS. + * the file name is chinese which has been encoded + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_GetDfsUriFromLocal_0014, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_GetDfsUriFromLocal_0014"; + const string uriStr = "file://docs/storage/Users/currentUser/Documents/1.txt"; + const int userId = 100; + + HmdfsUriInfo hui; + auto ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(hui.fileSize, 0); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0014"; + } + /** * @tc.name: remote_file_share_test_0012 * @tc.desc: Test function of TransRemoteUriToLocal() interface for SUCCESS. @@ -502,4 +570,74 @@ namespace { GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_TransRemoteUriToLocal_0015"; } + + /** + * @tc.name: remote_file_share_test_0016 + * @tc.desc: Test function of TransRemoteUriToLocal() interface for FAILURE. + * the inpute param is invalid + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_TransRemoteUriToLocal_0016, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_TransRemoteUriToLocal_0016"; + const vector uriList = {"FILE://docs/storage/Users/currentUser/Document/1.txt", + "file://docs/storage/Users/currentUser/Download/Subject/2.jpg", + "file://docs/storage/Users/currentUser/Document/Subject1/Subject2/1.txt", + "file://docs/storage/100/account/Document/Subject1/Subject2/1.txt"}; + string networkId = ""; + string deviceId = "001"; + vector resultList; + int ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_EQ(ret, EINVAL); + + networkId = "100"; + deviceId = ""; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_EQ(ret, EINVAL); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_TransRemoteUriToLocal_0016"; + } + + /** + * @tc.name: remote_file_share_test_0017 + * @tc.desc: Test function of TransRemoteUriToLocal() interface for FAILURE. + * the inpute param is invalid + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, remote_file_share_test_0017, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin remote_file_share_test_0017"; + vector uriList = {"file://docs/storage/Users/currentUser/./Document/1.txt"}; + const string networkId = "100"; + const string deviceId = "001"; + vector resultList; + int ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "datashare://docs/storage/Users/currentUser/Document/1.txt"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "file://media/Photo/12/IMG_12345_0011/test.jpg"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "file://docs/test/"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "file://docs/storage/"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end remote_file_share_test_0017"; +} } -- Gitee From 773c4b584098c298ea8dfe07e6497b3ace608e03 Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Thu, 8 Aug 2024 20:16:01 +0800 Subject: [PATCH 20/53] add afs new testcase Signed-off-by: lvyuanyuan Change-Id: I8ef43e8ae8c202e713a40edb95d56534b9b92ac5 --- .../file_share_permission_sup_test.cpp | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp index 25b889cef..01a820ef4 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp @@ -142,24 +142,24 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_002, unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ - memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); })), Return(1))); FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); policies[0].uri = policyUriChar; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ - memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); })), Return(1))); ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); policies[0].length = sizeof(policyUriChar); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ - memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); })), Return(1))); ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); @@ -188,8 +188,8 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_003, FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ - memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)).WillOnce(Return(E_PERMISSION)); FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); @@ -202,8 +202,8 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_003, errorResults.push_back(rlt); } - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ - memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_PARAMS))); @@ -236,8 +236,8 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_004, PolicyErrorResult rltOne = {.uri = string(policy.uri)}; std::deque errorResults; errorResults.push_back(rltOne); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ - memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(EPERM))); @@ -245,8 +245,8 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_004, EXPECT_EQ(ret, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value){ - memcpy_s(value, sizeof("false") ,"true", sizeof("true")); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_DEVICE_NOT_SUPPORT))); -- Gitee From 55e4611af5cbd727da5be6474989e9510332ab34 Mon Sep 17 00:00:00 2001 From: chen0088 Date: Sat, 10 Aug 2024 11:35:13 +0800 Subject: [PATCH 21/53] add ut Signed-off-by: chen0088 --- tests/unittests/backup_tools/BUILD.gn | 8 +- .../tools_op_incremental_backup_test.cpp | 397 +++++++++++++++++- 2 files changed, 402 insertions(+), 3 deletions(-) diff --git a/tests/unittests/backup_tools/BUILD.gn b/tests/unittests/backup_tools/BUILD.gn index ec2f582eb..0a0c1d50a 100644 --- a/tests/unittests/backup_tools/BUILD.gn +++ b/tests/unittests/backup_tools/BUILD.gn @@ -21,12 +21,16 @@ ohos_unittest("backup_tool_test") { sources = [ "${path_backup_mock}/b_filesystem/b_file_mock.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_backup_mock.cpp", "${path_backup}/tools/backup_tool/src/tools_op.cpp", "${path_backup}/tools/backup_tool/src/tools_op_backup.cpp", "${path_backup}/tools/backup_tool/src/tools_op_check_sa.cpp", "${path_backup}/tools/backup_tool/src/tools_op_help.cpp", - "${path_backup}/tools/backup_tool/src/tools_op_incremental_backup.cpp", "backup_tool/tools_op_backup_test.cpp", "backup_tool/tools_op_check_sa_test.cpp", "backup_tool/tools_op_help_test.cpp", @@ -37,9 +41,11 @@ ohos_unittest("backup_tool_test") { include_dirs = [ "${path_base}/include", + "${path_backup}/frameworks/native/backup_kit_inner/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", "${path_backup}/interfaces/inner_api/native/backup_kit_inner", "${path_backup}/tools/backup_tool/include", + "${path_backup}/tools/backup_tool/src", ] include_dirs += backup_mock_utils_include diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp index a4b754222..75727088e 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,7 +21,7 @@ #include "b_resources/b_constants.h" #include "tools_op.h" -#include "tools_op_incremental_backup.h" +#include "tools_op_incremental_backup.cpp" #include "utils_mock_global_variable.h" namespace OHOS::FileManagement::Backup { @@ -178,4 +178,397 @@ HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_03 } GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_backup_0300"; } + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0400 + * @tc.name: SUB_backup_tools_op_incremental_backup_0400 + * @tc.desc: 测试OnFileReady分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_restore_0400, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_restore_0400"; + try { + auto ctx = make_shared(); + BFileInfo fileInfo; + fileInfo.owner = "test"; + fileInfo.fileName = "/manage.json"; + fileInfo.sn = 1; + UniqueFd fd(open("textFile", O_RDONLY)); + UniqueFd manifestFd(open("textManifest", O_RDONLY)); + OnFileReady(ctx, fileInfo, move(fd), move(manifestFd)); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_restore_0400"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0500 + * @tc.name: SUB_backup_tools_op_incremental_backup_0500 + * @tc.desc: 测试OnBundleStarted分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0500, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0500"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0500"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0501 + * @tc.name: SUB_backup_tools_op_incremental_backup_0501 + * @tc.desc: 测试OnBundleStarted分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0501"; + try { + auto ctx = make_shared(); + ctx->SetBundleFinishedCount(1); + ErrCode err = -1; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0501"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0600 + * @tc.name: SUB_backup_tools_op_incremental_backup_0600 + * @tc.desc: 测试OnBundleFinished分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0600, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0600"; + try { + auto ctx = make_shared(); + ctx->SetBundleFinishedCount(1); + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0600"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0700 + * @tc.name: SUB_backup_tools_op_incremental_backup_0700 + * @tc.desc: 测试OnAllBundlesFinished分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0700, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0700"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0700"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0701 + * @tc.name: SUB_backup_tools_op_incremental_backup_0701 + * @tc.desc: 测试OnAllBundlesFinished分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0701, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0701"; + try { + auto ctx = make_shared(); + ErrCode err = -1; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0701"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0800 + * @tc.name: SUB_backup_tools_op_incremental_backup_0800 + * @tc.desc: 测试OnBackupServiceDied分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0800, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0800"; + try { + auto ctx = make_shared(); + OnBackupServiceDied(ctx); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0800"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0900 + * @tc.name: SUB_backup_tools_op_incremental_backup_0900 + * @tc.desc: 测试BackupToolDirSoftlinkToBackupDir分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0900, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0900"; + try { + BackupToolDirSoftlinkToBackupDir(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0900"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1000 + * @tc.name: SUB_backup_tools_op_incremental_backup_1000 + * @tc.desc: 测试GetLocalCapabilitiesIncremental分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1000"; + try { + auto ctx = make_shared(); + string pathCapFile = ""; + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times = {"100"}; + int32_t ret = GetLocalCapabilitiesIncremental(ctx, pathCapFile, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1000"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1001 + * @tc.name: SUB_backup_tools_op_incremental_backup_1001 + * @tc.desc: 测试GetLocalCapabilitiesIncremental分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1001"; + try { + auto ctx = make_shared(); + string pathCapFile = "/data/backup"; + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("100"); + times.push_back("200"); + int32_t ret = GetLocalCapabilitiesIncremental(ctx, pathCapFile, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1001"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1100 + * @tc.name: SUB_backup_tools_op_incremental_backup_1100 + * @tc.desc: 测试Init分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1100"; + try { + string pathCapFile = "/data/backup"; + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("100"); + times.push_back("200"); + int32_t ret = Init(pathCapFile, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1100"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1200 + * @tc.name: SUB_backup_tools_op_incremental_backup_1200 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1200"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1", "bundle2"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1200"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1201 + * @tc.name: SUB_backup_tools_op_incremental_backup_1201 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1201, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1201"; + try { + map> mapArgToVal = { + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1201"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1202 + * @tc.name: SUB_backup_tools_op_incremental_backup_1202 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1202, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1202"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1202"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1203 + * @tc.name: SUB_backup_tools_op_incremental_backup_1203 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1203, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1203"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1203"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From d570b3ef0e9af34f793a460f273a256104afb476 Mon Sep 17 00:00:00 2001 From: y30045862 Date: Tue, 6 Aug 2024 15:50:23 +0800 Subject: [PATCH 22/53] =?UTF-8?q?=E5=85=A8=E9=87=8F=E5=A4=87=E4=BB=BD?= =?UTF-8?q?=E8=BE=B9=E6=89=93=E5=8C=85=E8=BE=B9=E4=BC=A0=E9=80=92fd=20Sign?= =?UTF-8?q?ed-off-by:=20yangjingbo10=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I043917047c6c1dca4466547867775d6b9a34e372 --- .../native/backup_ext/include/ext_extension.h | 3 +- .../native/backup_ext/src/ext_extension.cpp | 120 ++++++++++++++---- utils/include/b_filesystem/b_dir.h | 2 +- utils/src/b_filesystem/b_dir.cpp | 61 ++++----- 4 files changed, 127 insertions(+), 59 deletions(-) diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index b93bdbb3e..0b64343e0 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -155,10 +155,11 @@ private: void AsyncTaskOnIncrementalBackup(); ErrCode IncrementalBigFileReady(const TarMap &pkgInfo, const vector &bigInfos, sptr proxy); - ErrCode BigFileReady(sptr proxy); + ErrCode BigFileReady(const TarMap &bigFileInfo, sptr proxy); void WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum); void RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum); void IncrementalPacket(const vector &infos, TarMap &tar, sptr proxy); + void DoPacket(const map &srcFiles, TarMap &tar, sptr proxy); /** * @brief extension incremental backup restore is done diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 723d18df1..9e1c8033e 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -352,36 +352,26 @@ static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) return ret; } -ErrCode BackupExtExtension::BigFileReady(sptr proxy) +ErrCode BackupExtExtension::BigFileReady(const TarMap &bigFileInfo, sptr proxy) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - UniqueFd fd(open(INDEX_FILE_BACKUP.data(), O_RDONLY)); - if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_BACKUP.c_str(), errno); - return BError::GetCodeByErrno(errno); - } - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - auto pkgInfo = cache.GetExtManageInfo(); - HILOGI("BigFileReady Begin: pkgInfo file size is: %{public}zu", pkgInfo.size()); + HILOGI("BigFileReady Begin: bigFileInfo file size is: %{public}zu", bigFileInfo.size()); ErrCode ret {ERR_OK}; auto startTime = std::chrono::system_clock::now(); int fdNum = 0; - for (auto &item : pkgInfo) { - if (item.hashName.empty() || item.fileName.empty()) { - continue; - } + for (auto &item : bigFileInfo) { WaitToSendFd(startTime, fdNum); int32_t errCode = ERR_OK; - UniqueFd fd(open(item.fileName.data(), O_RDONLY)); + string fllePath = std::get<0>(item.second); + UniqueFd fd(open(fllePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("open file failed, file name is %{public}s, err = %{public}d", item.fileName.c_str(), errno); + HILOGE("open file failed, file name is %{public}s, err = %{public}d", fllePath.c_str(), errno); errCode = errno; } - ret = proxy->AppFileReady(item.hashName, std::move(fd), errCode); + ret = proxy->AppFileReady(item.first, std::move(fd), errCode); if (SUCCEEDED(ret)) { - HILOGI("The application is packaged successfully, package name is %{public}s", item.hashName.c_str()); + HILOGI("The application is packaged successfully, package name is %{public}s", item.first.c_str()); } else { HILOGW("Current file execute app file ready interface failed, ret is:%{public}d", ret); } @@ -501,7 +491,7 @@ static bool IsUserTar(const string &tarFile, const std::vector &e return false; } -static pair> GetFileInfos(const vector &includes, const vector &excludes) +static pair> GetFileInfos(const vector &includes, const vector &excludes) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto [errCode, files, smallFiles] = BDir::GetBigFiles(includes, excludes); @@ -537,6 +527,76 @@ static pair> GetFileInfos(const vector &includes, return {bigFiles, smallFiles}; } +/** + * 全量tar包回传 + */ +static ErrCode TarFileReady(const TarMap &tarFileInfo, sptr proxy) +{ + if (tarFileInfo.empty()) { + HILOGI("TarFileReady: No tar file found"); + return ERR_OK; + } + string tarName = tarFileInfo.begin()->first; + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + string tarPath = path + tarName; + int32_t errCode = ERR_OK; + UniqueFd fd(open(tarPath.data(), O_RDONLY)); + if (fd < 0) { + HILOGE("TarFileReady open file failed, file name is %{public}s, err = %{public}d", tarName.c_str(), errno); + errCode = errno; + } + int ret = proxy->AppFileReady(tarName, std::move(fd), errCode); + if (SUCCEEDED(ret)) { + HILOGI("TarFileReady: AppFileReady success for %{public}s", tarName.c_str()); + // 删除文件 + RemoveFile(tarName); + } else { + HILOGE("TarFileReady AppFileReady fail to be invoked for %{public}s: ret = %{public}d", tarName.c_str(), ret); + } + return ret; +} + +void BackupExtExtension::DoPacket(const map &srcFiles, TarMap &tar, sptr proxy) +{ + HILOGI("DoPacket begin, infos count: %{public}zu", srcFiles.size()); + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + int64_t totalSize = 0; + uint32_t fileCount = 0; + vector packFiles; + TarFile::GetInstance().SetPacketMode(true); // 设置下打包模式 + auto startTime = std::chrono::system_clock::now(); + int fdNum = 0; + for (auto small : srcFiles) { + totalSize += small.second; + fileCount += 1; + packFiles.emplace_back(small.first); + if (totalSize >= DEFAULT_SLICE_SIZE || fileCount >= MAX_FILE_COUNT) { + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, "part", path, tarMap); + tar.insert(tarMap.begin(), tarMap.end()); + // 执行tar包回传功能 + WaitToSendFd(startTime, fdNum); + TarFileReady(tarMap, proxy); + totalSize = 0; + fileCount = 0; + packFiles.clear(); + fdNum += FILE_AND_MANIFEST_FD_COUNT; + RefreshTimeInfo(startTime, fdNum); + } + } + if (fileCount > 0) { + // 打包回传 + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, "part", path, tarMap); + TarFileReady(tarMap, proxy); + fdNum = 1; + WaitToSendFd(startTime, fdNum); + tar.insert(tarMap.begin(), tarMap.end()); + packFiles.clear(); + RefreshTimeInfo(startTime, fdNum); + } +} + int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -557,6 +617,11 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) vector includes = usrConfig.GetIncludes(); vector excludes = usrConfig.GetExcludes(); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + } + // 大文件处理 HILOGI("Start packet bigfiles and small files"); auto [bigFileInfo, smallFiles] = GetFileInfos(includes, excludes); @@ -567,21 +632,22 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) } } + // 回传大文件 + HILOGI("Will notify BigFileReady"); + auto res = BigFileReady(bigFileInfo, proxy); + HILOGI("Start packet Tar files"); - // 分片打包 + // 分片打包, 回传tar包 TarMap tarMap {}; - TarFile::GetInstance().Packet(smallFiles, "part", path, tarMap); + DoPacket(smallFiles, tarMap, proxy); bigFileInfo.insert(tarMap.begin(), tarMap.end()); - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); - } + HILOGI("Do backup, DoPacket end"); + HILOGI("Will notify IndexFileReady"); if (auto ret = IndexFileReady(bigFileInfo, proxy); ret) { return ret; } - HILOGI("Will notify BigFileReady"); - auto res = BigFileReady(proxy); + HILOGI("HandleBackup finish, ret = %{public}d", res); return res; } diff --git a/utils/include/b_filesystem/b_dir.h b/utils/include/b_filesystem/b_dir.h index 753529cb6..e1e728d29 100644 --- a/utils/include/b_filesystem/b_dir.h +++ b/utils/include/b_filesystem/b_dir.h @@ -46,7 +46,7 @@ public: * @param excludes 需要排除的文件及目录集合 * @return 错误码、大文件名集合 */ - static std::tuple, std::vector> GetBigFiles( + static std::tuple, std::map> GetBigFiles( const std::vector &includes, const std::vector &excludes); /** diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index 23d9b525c..d99581d28 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -55,10 +55,10 @@ static bool IsEmptyDirectory(const string &path) return isEmpty; } -static tuple, vector> GetFile(const string &path, off_t size = -1) +static tuple, map> GetFile(const string &path, off_t size = -1) { map files; - vector smallFiles; + map smallFiles; struct stat sta = {}; if (stat(path.data(), &sta) == -1) { return {BError(errno).GetCode(), files, smallFiles}; @@ -67,7 +67,7 @@ static tuple, vector> GetFile(const st return {BError(BError::Codes::OK).GetCode(), files, smallFiles}; } if (sta.st_size <= size) { - smallFiles.emplace_back(path); + smallFiles.insert(make_pair(path, sta.st_size)); } else { files.try_emplace(path, sta); } @@ -85,19 +85,19 @@ static uint32_t CheckOverLongPath(const string &path) return len; } -static tuple, vector> GetDirFilesDetail(const string &path, - bool recursion, - off_t size = -1) +static tuple, map> GetDirFilesDetail(const string &path, + bool recursion, + off_t size = -1) { map files; - vector smallFiles; + map smallFiles; if (IsEmptyDirectory(path)) { string newPath = path; if (path.at(path.size()-1) != '/') { newPath += '/'; } - smallFiles.emplace_back(newPath); + smallFiles.insert(make_pair(newPath, 0)); return {ERR_OK, files, smallFiles}; } @@ -111,32 +111,33 @@ static tuple, vector> GetDirFilesDetai // current dir OR parent dir if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { continue; - } else if (ptr->d_type == DT_DIR) { - if (!recursion) { - continue; - } - auto [errCode, subFiles, subSmallFiles] = - GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size); - if (errCode != 0) { - return {errCode, files, smallFiles}; - } - files.merge(subFiles); - smallFiles.insert(smallFiles.end(), subSmallFiles.begin(), subSmallFiles.end()); - } else if (ptr->d_type == DT_LNK) { - continue; - } else { + } else if (ptr->d_type == DT_REG) { struct stat sta = {}; string fileName = IncludeTrailingPathDelimiter(path) + string(ptr->d_name); if (CheckOverLongPath(fileName) >= PATH_MAX_LEN || stat(fileName.data(), &sta) == -1) { continue; } if (sta.st_size <= size) { - smallFiles.emplace_back(fileName); + smallFiles.insert(make_pair(fileName, sta.st_size)); continue; } files.try_emplace(fileName, sta); + } else if (ptr->d_type != DT_DIR) { + HILOGE("Not support file type"); + continue; + } + // DT_DIR type + if (!recursion) { + continue; } + auto [errCode, subFiles, subSmallFiles] = + GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size); + if (errCode != 0) { + return {errCode, files, smallFiles}; + } + files.merge(subFiles); + smallFiles.insert(subSmallFiles.begin(), subSmallFiles.end()); } return {ERR_OK, files, smallFiles}; } @@ -198,20 +199,20 @@ static set ExpandPathWildcard(const vector &vec, bool onlyPath) return filteredPath; } -tuple, vector> BDir::GetBigFiles(const vector &includes, - const vector &excludes) +tuple, map> BDir::GetBigFiles(const vector &includes, + const vector &excludes) { set inc = ExpandPathWildcard(includes, false); map incFiles; - vector incSmallFiles; + map incSmallFiles; for (const auto &item : inc) { auto [errCode, files, smallFiles] = GetDirFilesDetail(item, true, BConstants::BIG_FILE_BOUNDARY); if (errCode == 0) { int32_t num = static_cast(files.size()); incFiles.merge(move(files)); HILOGI("big files: %{public}d; small files: %{public}d", num, static_cast(smallFiles.size())); - incSmallFiles.insert(incSmallFiles.end(), smallFiles.begin(), smallFiles.end()); + incSmallFiles.insert(smallFiles.begin(), smallFiles.end()); } } @@ -234,10 +235,10 @@ tuple, vector> BDir::GetBigFiles(const return false; }; - vector resSmallFiles; + map resSmallFiles; for (const auto &item : incSmallFiles) { - if (!isMatch(excludes, item)) { - resSmallFiles.emplace_back(item); + if (!isMatch(excludes, item.first)) { + resSmallFiles.insert(make_pair(item.first, item.second)); } } -- Gitee From 106830c84b3c0b52f524492a3a7b25d3c5d2f2df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E6=99=9F=E9=92=B0?= Date: Thu, 8 Aug 2024 15:26:45 +0800 Subject: [PATCH 23/53] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=B5=81=E7=A8=8B?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E6=9C=AA=E4=B8=8A=E6=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张晟钰 --- .../native/backup_ext/src/ext_extension.cpp | 171 ++++++++++-------- services/backup_sa/src/module_ipc/service.cpp | 32 +++- 2 files changed, 121 insertions(+), 82 deletions(-) diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 723d18df1..4bbe90a3c 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -141,14 +141,14 @@ static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName) size_t filePathPrefix = filePath.find_last_of(BConstants::FILE_SEPARATOR_CHAR); if (filePathPrefix == string::npos) { HILOGE("GetFileHandleForSpecialCloneCloud: Invalid fileName"); - throw BError(BError::Codes::EXT_INVAL_ARG, fileName); + return UniqueFd(-1); } string path = filePath.substr(0, filePathPrefix); if (access(path.c_str(), F_OK) != 0) { bool created = ForceCreateDirectory(path.data()); if (!created) { - string str = string("Failed to create restore folder."); - throw BError(BError::Codes::EXT_INVAL_ARG, str); + HILOGE("Failed to create restore folder."); + return UniqueFd(-1); } } UniqueFd fd(open(fileName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); @@ -214,43 +214,47 @@ static string GetReportFileName(const string &fileName) static ErrCode GetIncreFileHandleForSpecialVersion(const string &fileName) { + HILOGI("extension:GetIncreFileHandleForSpecialVersion, filename:%{public}s", fileName.c_str()); + ErrCode errCode = ERR_OK; UniqueFd fd = GetFileHandleForSpecialCloneCloud(fileName); if (fd < 0) { HILOGE("Failed to open file = %{private}s, err = %{public}d", fileName.c_str(), errno); - throw BError(BError::Codes::EXT_INVAL_ARG, string("open tar file failed")); + errCode = errno; } string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { - string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); - throw BError(BError::Codes::EXT_INVAL_ARG, str); + HILOGE("Failed to create restore folder : %{private}s, err = %{public}d", path.c_str(), errno); + errCode = errno; } string reportName = path + BConstants::BLANK_REPORT_NAME; UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (reportFd < 0) { HILOGE("Failed to open report file = %{private}s, err = %{public}d", reportName.c_str(), errno); - throw BError(BError::Codes::EXT_INVAL_ARG, string("open report file failed")); + errCode = errno; } auto proxy = ServiceProxy::GetInstance(); if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + HILOGE("Failed to get file handle for special version clone"); + return BError(BError::Codes::EXT_BROKEN_BACKUP_SA).GetCode(); } - auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), ERR_OK); + auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), errCode); if (ret != ERR_OK) { HILOGE("Failed to AppIncrementalFileReady %{public}d", ret); } return ERR_OK; } -static string GetIncrementalFileHandlePath() +static string GetIncrementalFileHandlePath(const string &fileName) { string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); throw BError(BError::Codes::EXT_INVAL_ARG, str); } - return path; + string tarName = path + fileName; + return tarName; } ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) @@ -262,19 +266,18 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) extension_->GetExtensionAction()); throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); } - HILOGI("extension: Start GetIncrementalFileHandle"); VerifyCaller(); if (extension_->SpecialVersionForCloneAndCloud()) { return GetIncreFileHandleForSpecialVersion(fileName); } - HILOGI("extension: single to single fileName:%{public}s", GetAnonyPath(fileName).c_str()); - string path = GetIncrementalFileHandlePath(); - string tarName = path + fileName; + HILOGI("extension: GetIncrementalFileHandle single to single Name:%{public}s", GetAnonyPath(fileName).c_str()); + string tarName = GetIncrementalFileHandlePath(fileName); + int32_t errCode = ERR_OK; if (access(tarName.c_str(), F_OK) == 0) { - throw BError(BError::Codes::EXT_INVAL_ARG, string("The file already exists")); + HILOGE("The file already exists, tarname = %{private}s, err =%{public}d", tarName.c_str(), errno); + errCode = errno; } - int32_t errCode = ERR_OK; UniqueFd fd(open(tarName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (fd < 0) { HILOGE("Failed to open tar file = %{private}s, err = %{public}d", tarName.c_str(), errno); @@ -283,7 +286,8 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) // 对应的简报文件 string reportName = GetReportFileName(tarName); if (access(reportName.c_str(), F_OK) == 0) { - throw BError(BError::Codes::EXT_INVAL_ARG, string("The report file already exists")); + HILOGE("The report file already exists, Name = %{private}s, err =%{public}d", reportName.c_str(), errno); + errCode = errno; } UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (reportFd < 0) { @@ -303,24 +307,29 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) } catch (...) { HILOGE("Failed to get incremental file handle"); DoClear(); - return BError(BError::Codes::EXT_INVAL_ARG).GetCode(); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } } ErrCode BackupExtExtension::HandleClear() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - HILOGI("begin clear"); - if (extension_ == nullptr) { - HILOGE("Failed to handle clear, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { - return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + try { + HILOGI("begin clear"); + if (extension_ == nullptr) { + HILOGE("Failed to handle clear, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { + return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + } + VerifyCaller(); + DoClear(); + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle clear"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - VerifyCaller(); - DoClear(); - return ERR_OK; } static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) @@ -482,7 +491,7 @@ ErrCode BackupExtExtension::HandleBackup() .GetCode(); } AsyncTaskOnBackup(); - return 0; + return ERR_OK; } static bool IsUserTar(const string &tarFile, const std::vector &extManageInfo) @@ -1293,29 +1302,33 @@ void BackupExtExtension::AsyncTaskOnBackup() ErrCode BackupExtExtension::HandleRestore() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(); - if (extension_ == nullptr) { - HILOGE("Failed to handle restore, extension is nullptr"); - throw BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr"); - } - if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { - HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); - throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); - } - // read backup_config is allow to backup or restore - if (!extension_->AllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); - return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") - .GetCode(); - } + try { + VerifyCaller(); + if (extension_ == nullptr) { + HILOGE("Failed to handle restore, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { + HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); + return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + } + // read backup_config is allow to backup or restore + if (!extension_->AllowToBackupRestore()) { + HILOGE("Application does not allow backup or restore"); + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); + } - // async do restore. - if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) { - HILOGI("Restore directly when upgrading."); - AsyncTaskRestoreForUpgrade(); + // async do restore. + if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) { + HILOGI("Restore directly when upgrading."); + AsyncTaskRestoreForUpgrade(); + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle restore"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - - return 0; } static bool CheckTar(const string &fileName) @@ -1397,22 +1410,27 @@ void BackupExtExtension::CompareFiles(UniqueFd incrementalFd, ErrCode BackupExtExtension::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) { - HILOGI("Start HandleIncrementalBackup"); HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (extension_ == nullptr) { - HILOGE("Failed to handle incremental backup, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - string usrConfig = extension_->GetUsrConfig(); - BJsonCachedEntity cachedEntity(usrConfig); - auto cache = cachedEntity.Structuralize(); - if (!cache.GetAllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); - return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") - .GetCode(); + try { + HILOGI("Start HandleIncrementalBackup"); + if (extension_ == nullptr) { + HILOGE("Failed to handle incremental backup, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + string usrConfig = extension_->GetUsrConfig(); + BJsonCachedEntity cachedEntity(usrConfig); + auto cache = cachedEntity.Structuralize(); + if (!cache.GetAllowToBackupRestore()) { + HILOGE("Application does not allow backup or restore"); + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); + } + AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd)); + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle incremental backup"); + return BError(BError::Codes::EXT_INVAL_ARG).GetCode(); } - AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd)); - return 0; } ErrCode BackupExtExtension::IncrementalOnBackup() @@ -1431,7 +1449,7 @@ ErrCode BackupExtExtension::IncrementalOnBackup() .GetCode(); } AsyncTaskOnIncrementalBackup(); - return 0; + return ERR_OK; } tuple BackupExtExtension::GetIncrementalBackupFileHandle() @@ -1840,15 +1858,20 @@ ErrCode BackupExtExtension::GetBackupInfo(std::string &result) ErrCode BackupExtExtension::UpdateFdSendRate(std::string &bundleName, int32_t sendRate) { - std::lock_guard lock(updateSendRateLock_); - HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); - VerifyCaller(); - bundleName_ = bundleName; - sendRate_ = sendRate; - if (sendRate > 0) { - startSendFdRateCon_.notify_one(); + try { + std::lock_guard lock(updateSendRateLock_); + HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); + VerifyCaller(); + bundleName_ = bundleName; + sendRate_ = sendRate; + if (sendRate > 0) { + startSendFdRateCon_.notify_one(); + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to UpdateFdSendRate"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - return ERR_OK; } std::function BackupExtExtension::RestoreResultCallbackEx(wptr obj) diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index a896ceb52..30cdeba74 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -285,16 +285,27 @@ ErrCode Service::InitBackupSession(sptr remote) } catch (const BError &e) { StopAll(nullptr, true); return e.GetCode(); + } catch (const exception &e) { + HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + return EPERM; + } catch (...) { + HILOGI("Unexpected exception"); + return EPERM; } } ErrCode Service::Start() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(session_->GetScenario()); - session_->Start(); - OnStartSched(); - return BError(BError::Codes::OK); + try { + VerifyCaller(session_->GetScenario()); + session_->Start(); + OnStartSched(); + return BError(BError::Codes::OK); + } catch (const BError &e) { + HILOGE("Failde to Start"); + return e.GetCode(); + } } static bool SpecialVersion(const string &versionName) @@ -623,10 +634,15 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun ErrCode Service::Finish() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(session_->GetScenario()); - session_->Finish(); - OnAllBundlesFinished(BError(BError::Codes::OK)); - return BError(BError::Codes::OK); + try { + VerifyCaller(session_->GetScenario()); + session_->Finish(); + OnAllBundlesFinished(BError(BError::Codes::OK)); + return BError(BError::Codes::OK); + } catch (const BError &e) { + HILOGE("Failde to Finish"); + return e.GetCode(); + } } ErrCode Service::PublishFile(const BFileInfo &fileInfo) -- Gitee From 7fe296b9add1ab3bc9a3bcc47d52a05d6a6e2918 Mon Sep 17 00:00:00 2001 From: chen0088 Date: Sat, 10 Aug 2024 09:18:31 +0800 Subject: [PATCH 24/53] add ut Signed-off-by: chen0088 --- .../file_share_permission_test/BUILD.gn | 1 + .../file_share_permission_test.cpp | 281 +++++++++++++++++- 2 files changed, 281 insertions(+), 1 deletion(-) diff --git a/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn b/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn index a35a2c810..88e9a42ec 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn +++ b/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn @@ -27,6 +27,7 @@ ohos_unittest("file_share_permission_ndk_test") { include_dirs = [ "include", "${app_file_service_path}/interfaces/kits/ndk/fileshare/include", + "${app_file_service_path}/interfaces/kits/ndk/fileshare/src", "//third_party/googletest/include", ] resource_config_file = "../../resource/ohos_test.xml" diff --git a/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp index 0ac913e39..a68b23243 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp +++ b/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp @@ -30,7 +30,7 @@ #include "file_permission.h" #include "ipc_skeleton.h" #include "log.h" -#include "oh_file_share.h" +#include "oh_file_share.cpp" #include "parameter.h" #include "sandbox_helper.h" #include "uri.h" @@ -916,4 +916,283 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test } GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_004 end"; } + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0100 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0100 start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = { + .uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = sizeof(policies) / sizeof(policies[0]); + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0100 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0200 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0200() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0200 start"; + FileShare_PolicyInfo policy = { + .uri = nullptr, + .length = 1, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = 1; + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0200 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0300 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0300() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0300 start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = { + .uri = policyUriChar, + .length = 0, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = 1; + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0300 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0400 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0400() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0400 start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = { + .uri = policyUriChar, + .length = sizeof(policyUriChar) + 1, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = sizeof(policies) / sizeof(policies[0]); + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0400 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0100 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0100 start"; + std::deque errorResults; + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0100 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0200 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0200() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0200 start"; + std::deque errorResults; + for (int32_t i = 0; i <= FOO_MAX_LEN + 1; i++) { + OHOS::AppFileService::PolicyErrorResult errorResult; + errorResults.push_back(errorResult); + } + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0200 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0300 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0300() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0300 start"; + std::deque errorResults; + OHOS::AppFileService::PolicyErrorResult errorResult; + errorResults.push_back(errorResult); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_TRUE(ret); + if (result[0].uri != nullptr) { + free(result[0].uri); + } + if (result[0].message != nullptr) { + free(result[0].message); + } + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0300 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0400 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0400() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0400 start"; + std::deque errorResults; + OHOS::AppFileService::PolicyErrorResult errorResult; + errorResult.uri = "uri"; + errorResult.message = "message"; + errorResults.push_back(errorResult); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_TRUE(ret); + if (result[0].uri != nullptr) { + free(result[0].uri); + } + if (result[0].message != nullptr) { + free(result[0].message); + } + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0400 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResultBool_0100 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResultBool_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResultBool_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0100 start"; + std::vector errorResults; + bool *result = nullptr; + bool ret = ConvertPolicyErrorResultBool(errorResults, &result); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0100 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResultBool_0200 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResultBool_0200() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResultBool_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0200 start"; + std::vector errorResults(FOO_MAX_LEN + 1, true); + bool *result = nullptr; + bool ret = ConvertPolicyErrorResultBool(errorResults, &result); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0200 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResultBool_0300 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResultBool_0300() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResultBool_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0300 start"; + std::vector errorResults(1, true); + bool *result = nullptr; + bool ret = ConvertPolicyErrorResultBool(errorResults, &result); + EXPECT_TRUE(ret); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0300 end"; +} + +/** + * @tc.name: OH_FileShare_ErrorCodeConversion_0100 + * @tc.desc: Test function of OH_FileShare_ErrorCodeConversion_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ErrorCodeConversion_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ErrorCodeConversion_0100 start"; + EXPECT_EQ(ErrorCodeConversion(static_cast(E_NO_ERROR)), E_NO_ERROR); + EXPECT_EQ(ErrorCodeConversion(static_cast(E_PERMISSION)), E_PERMISSION); + EXPECT_EQ(ErrorCodeConversion(static_cast(E_PARAMS)), E_PARAMS); + EXPECT_EQ(ErrorCodeConversion(EPERM), E_EPERM); + EXPECT_EQ(ErrorCodeConversion(-EPERM), E_UNKNOWN_ERROR); + GTEST_LOG_(INFO) << "OH_FileShare_ErrorCodeConversion_0100 end"; +} } // namespace OHOS::AppFileService::ModuleFileSharePermission -- Gitee From 7690d4f825a445341861c9b0f66bb9b08102259f Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Mon, 12 Aug 2024 16:11:11 +0800 Subject: [PATCH 25/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: I872c50fc5c0ac9f624cf1e463c6647ceae7624d3 --- .../native/file_uri/src/file_uri.cpp | 2 +- .../file_uri_native/file_uri_test.cpp | 9 +++ tests/unittests/backup_ext/tar_file_test.cpp | 7 ++ tests/unittests/backup_sa/module_ipc/BUILD.gn | 1 + .../module_ipc/sched_scheduler_test.cpp | 69 +++++++++++++++++++ .../backup_sa/module_ipc/service_test.cpp | 62 +++++++++++++++++ 6 files changed, 149 insertions(+), 1 deletion(-) diff --git a/interfaces/innerkits/native/file_uri/src/file_uri.cpp b/interfaces/innerkits/native/file_uri/src/file_uri.cpp index 11fb261c6..3050f29a5 100644 --- a/interfaces/innerkits/native/file_uri/src/file_uri.cpp +++ b/interfaces/innerkits/native/file_uri/src/file_uri.cpp @@ -59,7 +59,7 @@ string FileUri::GetName() return ""; } - if (posLast == sandboxPath.size()) { + if (posLast == (sandboxPath.size() - 1)) { return ""; } diff --git a/test/unittest/file_uri_native/file_uri_test.cpp b/test/unittest/file_uri_native/file_uri_test.cpp index 45b5fe190..8e84576ff 100644 --- a/test/unittest/file_uri_native/file_uri_test.cpp +++ b/test/unittest/file_uri_native/file_uri_test.cpp @@ -106,6 +106,11 @@ namespace OHOS::AppFileService::ModuleFileUri { FileUri fileUri(fileStr); string name = fileUri.GetName(); EXPECT_EQ(name, "test.txt"); + + string fileStr2 = "/data/storage/el2/base/files/test.txt/"; + string uri2 = "file://" + BUNDLE_A + fileStr; + FileUri fileUri2(fileStr2); + EXPECT_EQ(fileUri2.GetName(), ""); GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetName_0000"; } @@ -130,6 +135,10 @@ namespace OHOS::AppFileService::ModuleFileUri { FileUri fileUri2(uri2); path = fileUri2.GetPath(); EXPECT_EQ(path, "/Photo/12/IMG_12345_999999"); + + string uri4 = "file://media/Photo/12/IMG_12345_999999"; + FileUri fileUri4(uri4); + EXPECT_EQ(fileUri2.GetPath(), "/Photo/12/IMG_12345_999999"); GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetPath_0000"; } diff --git a/tests/unittests/backup_ext/tar_file_test.cpp b/tests/unittests/backup_ext/tar_file_test.cpp index 5e8b37785..49d094a2f 100644 --- a/tests/unittests/backup_ext/tar_file_test.cpp +++ b/tests/unittests/backup_ext/tar_file_test.cpp @@ -104,6 +104,13 @@ HWTEST_F(TarFileTest, SUB_Tar_File_Packet_0100, testing::ext::TestSize.Level1) bool ret = TarFile::GetInstance().Packet(srcFiles, tarFileName, pkPath, tarMap); EXPECT_TRUE(tarMap.empty()); EXPECT_FALSE(ret); + + TestManager tm("SUB_Tar_File_Packet_0100"); + string root = tm.GetRootDirCurTest(); + pkPath = root; + ret = TarFile::GetInstance().Packet(srcFiles, tarFileName, pkPath, tarMap); + EXPECT_TRUE(tarMap.empty()); + EXPECT_FALSE(ret); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "TarFileTest-an exception occurred by TarFile."; diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 6a395d44a..9918de5e7 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -143,6 +143,7 @@ ohos_unittest("backup_service_test") { blocklist = "${path_backup}/cfi_blocklist.txt" } + defines = [ "private=public" ] use_exceptions = true } diff --git a/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp b/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp index 27273d9cf..505e0eb57 100644 --- a/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp @@ -121,6 +121,30 @@ HWTEST_F(SchedSchedulerTest, SUB_Service_Sched_0100, testing::ext::TestSize.Leve GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_Sched_0100"; } +/** + * @tc.number: SUB_Service_Sched_0200 + * @tc.name: SUB_Service_Sched_0200 + * @tc.desc: 测试 Sched接口,sessionPtr_为空场景 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SchedSchedulerTest, SUB_Service_Sched_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_Sched_0200"; + try { + sptr schedPtrNull = sptr(new SchedScheduler(wptr(servicePtr_), nullptr)); + schedPtrNull->Sched(); + schedPtrNull->ExecutingQueueTasks("test"); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by Sched."; + } + GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_Sched_0200"; +} + /** * @tc.number: SUB_Service_ExecutingQueueTasks_0100 * @tc.name: SUB_Service_ExecutingQueueTasks_0100 @@ -168,4 +192,49 @@ HWTEST_F(SchedSchedulerTest, SUB_Service_RemoveExtConn_0100, testing::ext::TestS } GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_RemoveExtConn_0100"; } + +/** + * @tc.number: SUB_Service_TryUnloadServiceTimer_0100 + * @tc.name: SUB_Service_TryUnloadServiceTimer_0100 + * @tc.desc: 测试 TryUnloadServiceTimer 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SchedSchedulerTest, SUB_Service_TryUnloadServiceTimer_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_TryUnloadServiceTimer_0100"; + try { + EXPECT_TRUE(schedPtr_ != nullptr); + schedPtr_->TryUnloadServiceTimer(true); + schedPtr_->TryUnloadServiceTimer(false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by TryUnloadServiceTimer."; + } + GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_TryUnloadServiceTimer_0100"; +} + +/** + * @tc.number: SUB_Service_TryUnloadService_0100 + * @tc.name: SUB_Service_TryUnloadServicer_0100 + * @tc.desc: 测试 TryUnloadService 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SchedSchedulerTest, SUB_Service_TryUnloadService_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_TryUnloadService_0100"; + try { + EXPECT_TRUE(schedPtr_ != nullptr); + schedPtr_->TryUnloadService(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by TryUnloadService."; + } + GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_TryUnloadService_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index f2e6511c8..8f9e52159 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -441,6 +441,43 @@ HWTEST_F(ServiceTest, SUB_Service_AppDone_0102, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppDone_0102"; } +/** + * @tc.number: SUB_Service_ServiceResultReport_0000 + * @tc.name: SUB_Service_ServiceResultReport_0000 + * @tc.desc: 测试 ServiceResultReport 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_ServiceResultReport_0000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ServiceResultReport_0000"; + try { + GTEST_LOG_(INFO) << "SUB_Service_ServiceResultReport Branches Start"; + string bundleName = ""; + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::FULL_RESTORE, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::INCREMENTAL_RESTORE, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::FULL_BACKUP, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::INCREMENTAL_BACKUP, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", static_cast(1000), 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ServiceResultReport."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ServiceResultReport_0000"; +} + /** * @tc.number: SUB_Service_LaunchBackupExtension_0100 * @tc.name: SUB_Service_LaunchBackupExtension_0100 @@ -945,4 +982,29 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0100, testing::ext::TestSize.Level } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UpdateTimer_0100"; } + +/** + * @tc.number: SUB_Service_GetBackupInfoCmdHandle_0100 + * @tc.name: SUB_Service_GetBackupInfoCmdHandle_0100 + * @tc.desc: 测试 GetBackupInfoCmdHandle 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetBackupInfoCmdHandle_0100"; + try { + std::string bundleName = "com.example.app2backup"; + std::string result; + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); + EXPECT_TRUE(ret != BError::BackupErrorCode::E_INVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfoCmdHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfoCmdHandle_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From 92718171aef4185d750e3ad1470c0e8bf728017e Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Mon, 12 Aug 2024 16:18:39 +0800 Subject: [PATCH 26/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: I78dfae2b2fdcfcd391e4ace93e1c625a99417c67 --- tests/unittests/backup_sa/module_ipc/service_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index 8f9e52159..90797fb39 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -1000,7 +1000,7 @@ HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0100, testing::ext::Tes std::string result; EXPECT_TRUE(servicePtr_ != nullptr); auto ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); - EXPECT_TRUE(ret != BError::BackupErrorCode::E_INVAL); + EXPECT_TRUE(ret == BError::BackupErrorCode::E_INVAL); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfoCmdHandle."; -- Gitee From 44c47766729e41c04c982429d586673136f98673 Mon Sep 17 00:00:00 2001 From: "yaoruozi1@huawei.com" Date: Tue, 13 Aug 2024 09:29:48 +0800 Subject: [PATCH 27/53] =?UTF-8?q?=E9=80=82=E9=85=8D=E8=BF=9B=E5=BA=A6?= =?UTF-8?q?=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yaoruozi1@huawei.com --- .../native/backup_ext/include/ext_backup.h | 5 ++ .../native/backup_ext/include/ext_backup_js.h | 8 +- .../native/backup_ext/include/ext_extension.h | 13 +++- .../backup_ext/include/ext_extension_stub.h | 1 + .../native/backup_ext/src/ext_backup.cpp | 6 ++ .../native/backup_ext/src/ext_backup_js.cpp | 32 ++++++++ .../native/backup_ext/src/ext_extension.cpp | 50 +++++++++++++ .../backup_ext/src/ext_extension_stub.cpp | 16 ++++ .../include/service_reverse.h | 4 + .../include/service_reverse_stub.h | 5 ++ .../src/service_incremental_reverse.cpp | 20 +++++ .../backup_kit_inner/src/service_proxy.cpp | 27 +++++++ .../backup_kit_inner/src/service_reverse.cpp | 20 +++++ .../src/service_reverse_stub.cpp | 73 +++++++++++++++---- .../backup_ext/backup_extension_ability.js | 4 + .../impl/b_incremental_backup_session.h | 1 + .../impl/b_incremental_restore_session.h | 1 + .../backup_kit_inner/impl/b_session_backup.h | 1 + .../backup_kit_inner/impl/i_extension.h | 1 + .../impl/i_extension_ipc_interface_code.h | 1 + .../native/backup_kit_inner/impl/i_service.h | 1 + .../impl/i_service_ipc_interface_code.h | 1 + .../backup_kit_inner/impl/i_service_reverse.h | 4 + .../i_service_reverse_ipc_interface_code.h | 4 + .../backup_kit_inner/impl/service_proxy.h | 1 + interfaces/kits/js/backup/general_callbacks.h | 4 +- .../js/backup/session_backup_n_exporter.cpp | 31 +++++++- .../session_incremental_backup_n_exporter.cpp | 31 +++++++- .../js/backup/session_restore_n_exporter.cpp | 31 +++++++- .../backup_sa/include/module_ipc/service.h | 1 + .../module_ipc/service_reverse_proxy.h | 4 + .../include/module_ipc/service_stub.h | 1 + services/backup_sa/src/module_ipc/service.cpp | 26 +++++++ .../backup_sa/src/module_ipc/service_stub.cpp | 16 ++++ tools/backup_tool/src/tools_op_backup.cpp | 8 +- .../src/tools_op_incremental_backup.cpp | 8 +- .../src/tools_op_incremental_restore.cpp | 8 +- .../tools_op_incremental_restore_async.cpp | 11 ++- tools/backup_tool/src/tools_op_restore.cpp | 8 +- .../src/tools_op_restore_async.cpp | 8 +- utils/include/b_resources/b_constants.h | 4 + 41 files changed, 474 insertions(+), 26 deletions(-) diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h index dae003248..abfc0a18c 100644 --- a/frameworks/native/backup_ext/include/ext_backup.h +++ b/frameworks/native/backup_ext/include/ext_backup.h @@ -146,6 +146,11 @@ public: */ virtual ErrCode GetBackupInfo(std::function callback); + /** + * @brief Called do OnProcess + */ + virtual ErrCode OnProcess(std::function callback); + /** * @brief 数据迁移判断 * diff --git a/frameworks/native/backup_ext/include/ext_backup_js.h b/frameworks/native/backup_ext/include/ext_backup_js.h index cd32e0ce4..411f48dca 100644 --- a/frameworks/native/backup_ext/include/ext_backup_js.h +++ b/frameworks/native/backup_ext/include/ext_backup_js.h @@ -123,6 +123,13 @@ public: */ ErrCode InvokeAppExtMethod(ErrCode, const std::string) override; + /** + * @brief get app onProcess info + * + * @param callback The callBack. + */ + ErrCode OnProcess(std::function callback) override; + public: explicit ExtBackupJs(AbilityRuntime::JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {} ~ExtBackupJs() @@ -141,7 +148,6 @@ private: std::function &argv)> ParseRestoreInfo(); std::function &argv)> ParseBackupExInfo(); - std::function &argv)> ParseBackupInfo(); ErrCode CallJSRestoreEx(); ErrCode CallJSRestore(); diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index b93bdbb3e..368e2683c 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -32,6 +32,7 @@ #include "i_service.h" #include "tar_file.h" #include "thread_pool.h" +#include "timer.h" #include "unique_fd.h" namespace OHOS::FileManagement::Backup { @@ -51,6 +52,7 @@ public: ErrCode IncrementalOnBackup() override; std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; + ErrCode GetBundleProcessInfo(); ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; void AsyncTaskRestoreForUpgrade(void); @@ -112,6 +114,14 @@ private: void AppResultReport(const std::string restoreRetInfo, BackupRestoreScenario scenario, ErrCode errCode = 0); + /** + * @brief extension backup restore is done + * + * @param restoreRetInfo app restore reportInfo + */ + void ReportAppProcessInfo(const std::string restoreRetInfo, BackupRestoreScenario scenario, + ErrCode errCode = 0); + /** * @brief Executing Backup Tasks Asynchronously * @@ -198,15 +208,16 @@ private: std::shared_mutex lock_; std::shared_ptr extension_; std::string backupInfo_; + std::string bundleProcessInfo_; OHOS::ThreadPool threadPool_; std::mutex updateSendRateLock_; - std::atomic isStopSendFd_ {false}; std::condition_variable startSendFdRateCon_; std::condition_variable waitSendFdCon_; std::mutex startSendMutex_; std::mutex waitTimeLock_; std::string bundleName_; int32_t sendRate_ = BConstants::DEFAULT_FD_SEND_RATE; + Utils::Timer extTime_ {"queryOnProcessTimer"}; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/ext_extension_stub.h b/frameworks/native/backup_ext/include/ext_extension_stub.h index 86949011a..1e8720dff 100644 --- a/frameworks/native/backup_ext/include/ext_extension_stub.h +++ b/frameworks/native/backup_ext/include/ext_extension_stub.h @@ -42,6 +42,7 @@ private: ErrCode CmdIncrementalOnBackup(MessageParcel &data, MessageParcel &reply); ErrCode CmdGetIncrementalBackupFileHandle(MessageParcel &data, MessageParcel &reply); ErrCode CmdGetBackupInfo(MessageParcel &data, MessageParcel &reply); + ErrCode CmdGetProcessInfo(MessageParcel &data, MessageParcel &reply); ErrCode CmdUpdateFdSendRate(MessageParcel &data, MessageParcel &reply); private: diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index 280518596..5ccb1a3dc 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -291,4 +291,10 @@ ErrCode ExtBackup::InvokeAppExtMethod(ErrCode errCode, const std::string result) return ERR_OK; } +ErrCode ExtBackup::OnProcess(std::function callback) +{ + HILOGI("BackupExtensionAbility(base) OnProcess."); + return ERR_OK; +} + } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_backup_js.cpp b/frameworks/native/backup_ext/src/ext_backup_js.cpp index bb3de776c..183a36d22 100644 --- a/frameworks/native/backup_ext/src/ext_backup_js.cpp +++ b/frameworks/native/backup_ext/src/ext_backup_js.cpp @@ -838,4 +838,36 @@ ErrCode ExtBackupJs::InvokeAppExtMethod(ErrCode errCode, const std::string resul HILOGI("End Get App onBackupEx/onRestoreEx method result"); return ERR_OK; } + +ErrCode ExtBackupJs::OnProcess(std::function callback) +{ + HILOGI("BackupExtensionAbility(JS) OnProcess begin."); + BExcepUltils::BAssert(jsObj_, BError::Codes::EXT_BROKEN_FRAMEWORK, + "The app does not provide the OnProcess interface."); + callbackInfoBackup_ = std::make_shared(callback); + auto retParser = [jsRuntime {&jsRuntime_}, callBackInfo {callbackInfoBackup_}](napi_env env, + napi_value result) -> bool { + if (!CheckPromise(env, result)) { + size_t strLen = 0; + napi_status status = napi_get_value_string_utf8(env, result, nullptr, -1, &strLen); + if (status != napi_ok) { + return false; + } + size_t bufLen = strLen + 1; + unique_ptr str = make_unique(bufLen); + status = napi_get_value_string_utf8(env, result, str.get(), bufLen, &strLen); + callBackInfo->callbackParam(BError(BError::Codes::OK), str.get()); + return true; + } + HILOGI("BackupExtensionAbulity(JS) OnProcess ok."); + return CallPromiseEx(*jsRuntime, result, callBackInfo.get()); + }; + + auto errCode = CallJsMethod("onProcess", jsRuntime_, jsObj_.get(), {}, retParser); + if (errCode != ERR_OK) { + HILOGE("CallJsMethod error, code:%{public}d.", errCode); + } + HILOGI("BackupExtensionAbulity(JS) OnProcess end."); + return errCode; +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 723d18df1..1f658e569 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -2015,4 +2015,54 @@ void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point & fdSendNum = 0; } } + +ErrCode BackupExtExtension::GetBundleProcessInfo(std::string &result) +{ + auto obj = wptr(this); + auto ptr = obj.promote(); + if (ptr == nullptr) { + HILOGE("Failed to get ext extension."); + return BError(BError::Codes::EXT_INVAL_ARG, "extension GetBundleProcessInfo exception").GetCode(); + } + if (ptr->extension_ == nullptr) { + HILOGE("Failed to get extension."); + return BError(BError::Codes::EXT_INVAL_ARG, "extension GetBundleProcessInfo exception").GetCode(); + } + auto onProcessCallBack = [ptr](ErrCode errCode, const std::string result) { + if (ptr == nullptr) { + HILOGE("Failed to get ext extension."); + return; + } + HILOGI("GetBundleProcessInfo start. result = %{public}s", result.c_str()); + ptr->bundleProcessInfo_ = result; + }; + auto ret = ptr->extension_->OnProcess(onProcessCallBack); + if (ret != ERR_OK) { + HILOGE("Failed to get bundleProcessInfo. err = %{public}d", ret); + return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + } + HILOGD("bundleProcessInfo = %s", bundleProcessInfo_.c_str()); + result = bundleProcessInfo_; + if (!result.size()) { + + } else { + + } + backupInfo_.clear(); + + return ERR_OK; +} + +void BackupExtExtension::ReportAppProcessInfo(const std::string restoreRetInfo, BackupRestoreScenario scenario, ErrCode errCode) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGE("ReportAppProcessInfo error, proxy is empty"); + } + auto ret = proxy->ServiceResultReport(restoreRetInfo, scenario, errCode); + if (ret != ERR_OK) { + HILOGE("Failed notify app restoreResultReport, errCode: %{public}d", ret); + } + +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension_stub.cpp b/frameworks/native/backup_ext/src/ext_extension_stub.cpp index 6930c2982..667af89c2 100644 --- a/frameworks/native/backup_ext/src/ext_extension_stub.cpp +++ b/frameworks/native/backup_ext/src/ext_extension_stub.cpp @@ -47,6 +47,8 @@ ExtExtensionStub::ExtExtensionStub() &ExtExtensionStub::CmdGetIncrementalBackupFileHandle; opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_GET_BACKUP_INFO)] = &ExtExtensionStub::CmdGetBackupInfo; + opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_GET_PROCESS_INFO)] = + &ExtExtensionStub::CmdGetProcessInfo; opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_INCREMENTAL_ON_BACKUP)] = &ExtExtensionStub::CmdIncrementalOnBackup; opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_UPDATE_FD_SENDRATE)] = @@ -239,4 +241,18 @@ ErrCode ExtExtensionStub::CmdUpdateFdSendRate(MessageParcel &data, MessageParcel } return BError(BError::Codes::OK); } + +ErrCode ExtExtensionStub::CmdGetProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("CmdGetProcessInfo Begin"); + std::string result; + int ret = GetBackupInfo(result); + if (!reply.WriteInt32(ret)) { + return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the ret").GetCode(); + } + if (!reply.WriteString(result)) { + return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the result").GetCode(); + } + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/include/service_reverse.h b/frameworks/native/backup_kit_inner/include/service_reverse.h index 178bac3c9..3ecb58eab 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse.h @@ -30,6 +30,7 @@ public: void BackupOnResultReport(std::string result, std::string bundleName) override; void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void BackupOnAllBundlesFinished(int32_t errCode) override; + void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; @@ -37,6 +38,7 @@ public: void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) override; void RestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode = 0) override; + void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, int32_t errCode) override; @@ -44,6 +46,7 @@ public: void IncrementalBackupOnResultReport(std::string result, std::string bundleName) override; void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; + void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; @@ -52,6 +55,7 @@ public: int32_t errCode) override; void IncrementalRestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode = 0) override; + void IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; public: ServiceReverse() = delete; diff --git a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h index 879eccf1b..0384c0130 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h @@ -39,24 +39,29 @@ private: int32_t CmdBackupOnResultReport(MessageParcel &data, MessageParcel &reply); int32_t CmdBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); + int32_t CmdBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnFileReady(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnResultReport(MessageParcel &data, MessageParcel &reply); + int32_t CmdRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnFileReady(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnResultReport(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnFileReady(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnResultReport(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply); + void ServiceReverseStubSupplement(); }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp index 8c5f4c465..1e281c7f3 100644 --- a/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp +++ b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp @@ -70,6 +70,16 @@ void ServiceReverse::IncrementalBackupOnAllBundlesFinished(int32_t errCode) callbacksIncrementalBackup_.onAllBundlesFinished(errCode); } +void ServiceReverse::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("errCode = %{public}d", errCode); + if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onProcess) { + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); + return; + } + callbacksIncrementalBackup_.onProcess(bundleName, processInfo); +} + void ServiceReverse::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onBundleStarted) { @@ -125,6 +135,16 @@ void ServiceReverse::IncrementalRestoreOnResultReport(std::string result, std::s callbacksIncrementalRestore_.onBundleFinished(errCode, bundleName); } +void ServiceReverse::IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("begin incremental restore on result report, bundleName:%{public}s", bundleName.c_str()); + if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onProcess) { + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); + return; + } + callbacksIncrementalRestore_.onProcess(bundleName, processInfo); +} + ServiceReverse::ServiceReverse(BIncrementalBackupSession::Callbacks callbacks) : scenario_(Scenario::BACKUP), callbacksIncrementalBackup_(callbacks) { diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 1d004e4f1..e15ccdf9f 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -585,4 +585,31 @@ ErrCode ServiceProxy::UpdateSendRate(std::string &bundleName, int32_t sendRate, HILOGI("ServiceProxy UpdateSendRate end. ret = %{public}d", ret); return BError(BError::Codes::OK, "success"); } + +ErrCode ServiceProxy::ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) +{ + HILOGD("ServiceProxy NotifyBundleProcessInfo Begin."); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + if (!data.WriteString(processInfo)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleName").GetCode(); + } + if (!data.WriteInt32(static_cast(scenario))) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the scenario").GetCode(); + } + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()-> SendRequest(static_cast( + IServiceInterfaceCode::SERVICE_CMD_NOTIFY_BUNDLE_PROCESS_INFO), data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + HILOGI("ServiceProxy NotifyBundleProcessInfo end. ret = %{public}d", ret); + return BError(BError::Codes::OK, "success"); +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/src/service_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_reverse.cpp index f2e2eb716..dfc19ba25 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse.cpp @@ -69,6 +69,16 @@ void ServiceReverse::BackupOnAllBundlesFinished(int32_t errCode) callbacksBackup_.onAllBundlesFinished(errCode); } +void ServiceReverse::BackupOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("errCode = %{public}d", errCode); + if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onProcess) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksBackup_.onProcess(bundleName, processInfo); +} + void ServiceReverse::RestoreOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleStarted) { @@ -125,6 +135,16 @@ void ServiceReverse::RestoreOnResultReport(string result, std::string bundleName callbacksRestore_.onBundleFinished(errCode, bundleName); } +void ServiceReverse::RestoreOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("errCode = %{public}d", errCode); + if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onProcess) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksRestore_.onProcess(bundleName, processInfo); +} + ServiceReverse::ServiceReverse(BSessionBackup::Callbacks callbacks) : scenario_(Scenario::BACKUP), callbacksBackup_(callbacks) { diff --git a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp index 0fdeed6c8..506f3ce24 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp @@ -43,6 +43,26 @@ int32_t ServiceReverseStub::OnRemoteRequest(uint32_t code, } return (this->*(interfaceIndex->second))(data, reply); } +void ServiceReverseStub::ServiceReverseStubSupplement() +{ + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY)] = + &ServiceReverseStub::CmdIncrementalRestoreOnFileReady; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_RESULT_REPORT)] = + &ServiceReverseStub::CmdIncrementalRestoreOnResultReport; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnBundleFinished; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnAllBundlesFinished; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdIncrementalRestoreOnProcessInfo; +} ServiceReverseStub::ServiceReverseStub() { @@ -56,6 +76,8 @@ ServiceReverseStub::ServiceReverseStub() &ServiceReverseStub::CmdBackupOnBundleFinished; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_TASK_FINISHED)] = &ServiceReverseStub::CmdBackupOnAllBundlesFinished; + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdBackupOnProcessInfo; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_FILE_READY)] = &ServiceReverseStub::CmdRestoreOnFileReady; @@ -67,6 +89,8 @@ ServiceReverseStub::ServiceReverseStub() &ServiceReverseStub::CmdRestoreOnBundleFinished; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_TASK_FINISHED)] = &ServiceReverseStub::CmdRestoreOnAllBundlesFinished; + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdRestoreOnProcessInfo; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY)] = &ServiceReverseStub::CmdIncrementalBackupOnFileReady; @@ -81,21 +105,10 @@ ServiceReverseStub::ServiceReverseStub() opToInterfaceMap_[static_cast( IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED)] = &ServiceReverseStub::CmdIncrementalBackupOnAllBundlesFinished; - - opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY)] = - &ServiceReverseStub::CmdIncrementalRestoreOnFileReady; - opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED)] = - &ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted; - opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_RESULT_REPORT)] = - &ServiceReverseStub::CmdIncrementalRestoreOnResultReport; opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED)] = - &ServiceReverseStub::CmdIncrementalRestoreOnBundleFinished; - opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED)] = - &ServiceReverseStub::CmdIncrementalRestoreOnAllBundlesFinished; + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdIncrementalBackupOnProcessInfo; + ServiceReverseStubSupplement(); } int32_t ServiceReverseStub::CmdBackupOnFileReady(MessageParcel &data, MessageParcel &reply) @@ -143,6 +156,14 @@ int32_t ServiceReverseStub::CmdBackupOnAllBundlesFinished(MessageParcel &data, M return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string processInfo = data.ReadString(); + BackupOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) { int32_t errCode = data.ReadInt32(); @@ -198,6 +219,14 @@ int32_t ServiceReverseStub::CmdRestoreOnResultReport(MessageParcel &data, Messag return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string processInfo = data.ReadString(); + RestoreOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdIncrementalBackupOnFileReady(MessageParcel &data, MessageParcel &reply) { auto bundleName = data.ReadString(); @@ -245,6 +274,14 @@ int32_t ServiceReverseStub::CmdIncrementalBackupOnAllBundlesFinished(MessageParc return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdIncrementalBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string processInfo = data.ReadString(); + IncrementalBackupOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) { int32_t errCode = data.ReadInt32(); @@ -292,4 +329,12 @@ int32_t ServiceReverseStub::CmdIncrementalRestoreOnResultReport(MessageParcel &d IncrementalRestoreOnResultReport(result, bundleName, errCode); return BError(BError::Codes::OK); } + +int32_t ServiceReverseStub::CmdIncrementalRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + auto bundleName = data.ReadString(); + auto processInfo = data.ReadString(); + IncrementalRestoreOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/interfaces/api/js/napi/backup_ext/backup_extension_ability.js b/interfaces/api/js/napi/backup_ext/backup_extension_ability.js index b1801058f..acc2b4971 100644 --- a/interfaces/api/js/napi/backup_ext/backup_extension_ability.js +++ b/interfaces/api/js/napi/backup_ext/backup_extension_ability.js @@ -29,6 +29,10 @@ class BackupExtensionAbility { onRestoreEx(versionBackupedBundle, restoreInfo) { console.log(); } + + onProcess() { + console.log(); + } } export default BackupExtensionAbility \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h index f37aa190e..0c0005483 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h @@ -37,6 +37,7 @@ public: std::function onAllBundlesFinished; // 当整个备份流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用备份流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 某个应用上报执行进度的的回调函数 }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h index 54b3a25b1..34f5d9074 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h @@ -37,6 +37,7 @@ public: std::function onAllBundlesFinished; // 当整个恢复流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用恢复流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 某个应用上报执行进度的的回调函数 }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h index 46a6e24b1..2ddf9d92c 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h @@ -35,6 +35,7 @@ public: std::function onAllBundlesFinished; // 当整个备份流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用备份流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 某个应用上报执行进度的的回调函数 }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h index 364214d2d..732ee591f 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h @@ -39,6 +39,7 @@ public: virtual ErrCode IncrementalOnBackup() = 0; virtual std::tuple GetIncrementalBackupFileHandle() = 0; virtual ErrCode GetBackupInfo(std::string &result) = 0; + virtual ErrCode GetBackupInfo(std::string &processInfo) = 0; virtual ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) = 0; }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h index 15478e015..77f4281bd 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h @@ -31,6 +31,7 @@ enum class IExtensionInterfaceCode { CMD_GET_BACKUP_INFO, CMD_INCREMENTAL_ON_BACKUP, CMD_UPDATE_FD_SENDRATE, + CMD_GET_PROCESS_INFO, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h index 49348fb58..c43b647c7 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h @@ -85,6 +85,7 @@ public: virtual ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) = 0; virtual ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) = 0; virtual ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) = 0; + virtual ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Backup.IService") }; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h index 1de4b9c45..d4701bbc6 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h @@ -47,6 +47,7 @@ enum class IServiceInterfaceCode { SERVICE_CMD_UPDATE_TIMER, SERVICE_CMD_UPDATE_SENDRATE, SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP, + SERVICE_CMD_REPORT_BUNDLE_PROCESS_INFO, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h index 8791c26b2..ddd1f5c84 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h @@ -37,6 +37,7 @@ public: virtual void BackupOnResultReport(std::string result, std::string bundleName) = 0; virtual void BackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void BackupOnAllBundlesFinished(int32_t errCode) = 0; + virtual void BackupOnProcessInfo(std::string bundleName, std::string processInfo) = 0; virtual void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) = 0; @@ -44,6 +45,7 @@ public: ErrCode errCode = 0) = 0; virtual void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void RestoreOnAllBundlesFinished(int32_t errCode) = 0; + virtual void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) = 0; virtual void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, @@ -51,6 +53,7 @@ public: virtual void IncrementalBackupOnResultReport(std::string result, std::string bundleName) = 0; virtual void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalBackupOnAllBundlesFinished(int32_t errCode) = 0; + virtual void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) = 0; virtual void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalRestoreOnFileReady(std::string bundleName, @@ -61,6 +64,7 @@ public: ErrCode errCode = 0) = 0; virtual void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) = 0; + virtual void IncrementalRestoreOnProcessInfo(const std::string &bundleName, const std::string &processInfo) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileManagement.Backup.IServiceReverse") }; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h index a41ec673f..5d991d6fb 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h @@ -24,21 +24,25 @@ enum class IServiceReverseInterfaceCode { SERVICER_BACKUP_ON_SUB_TASK_FINISHED, SERVICER_BACKUP_ON_TASK_FINISHED, SERVICER_BACKUP_ON_RESULT_REPORT, + SERVICER_BACKUP_ON_PROCESS_INFO, SERVICER_RESTORE_ON_SUB_TASK_STARTED, SERVICER_RESTORE_ON_SUB_TASK_FINISHED, SERVICER_RESTORE_ON_TASK_FINISHED, SERVICER_RESTORE_ON_FILE_READY, SERVICER_RESTORE_ON_RESULT_REPORT, + SERVICER_RESTORE_ON_PROCESS_INFO, SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY, SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_STARTED, SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_FINISHED, SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED, SERVICER_INCREMENTAL_BACKUP_ON_RESULT_REPORT, + SERVICER_INCREMENTAL_BACKUP_ON_PROCESS_INFO, SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED, SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED, SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED, SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY, SERVICER_INCREMENTAL_RESTORE_ON_RESULT_REPORT, + SERVICER_INCREMENTAL_RESTORE_ON_PROCESS_INFO, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h index d0845087e..c50334b0e 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h @@ -68,6 +68,7 @@ public: ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) override; ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override; ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override; + ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) override; public: explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} diff --git a/interfaces/kits/js/backup/general_callbacks.h b/interfaces/kits/js/backup/general_callbacks.h index 04956ac66..2c0dd0ad3 100644 --- a/interfaces/kits/js/backup/general_callbacks.h +++ b/interfaces/kits/js/backup/general_callbacks.h @@ -43,7 +43,8 @@ public: onBundleEnd(env, thisPtr, jsCallbacks.GetProp("onBundleEnd")), onAllBundlesEnd(env, thisPtr, jsCallbacks.GetProp("onAllBundlesEnd")), onBackupServiceDied(env, thisPtr, jsCallbacks.GetProp("onBackupServiceDied")), - onResultReport(env, thisPtr, jsCallbacks.GetProp("onResultReport")) {}; + onResultReport(env, thisPtr, jsCallbacks.GetProp("onResultReport")), + onProcess(env, thisPtr, jsCallbacks.GetProp("onProcess")) {}; public: LibN::NAsyncWorkCallback onFileReady; @@ -52,6 +53,7 @@ public: LibN::NAsyncWorkCallback onAllBundlesEnd; LibN::NAsyncWorkCallback onBackupServiceDied; BackupRestoreCallback onResultReport; + LibN::NAsyncWorkCallback onProcess; }; } // namespace OHOS::FileManagement::Backup #endif // INTERFACES_KITS_JS_SRC_MOD_BACKUP_PROPERTIES_GENERAL_CALLBACKS_H \ No newline at end of file diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_backup_n_exporter.cpp index 0d84c0308..337ebb1e8 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_backup_n_exporter.cpp @@ -248,6 +248,34 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) callbacks->onBackupServiceDied.ThreadSafeSchedule(cbCompl); } +static void OnProcess(weak_ptr pCallbacks, const BundleName name, const std::string processInfo) +{ + HILOGI("Callback OnProcess, bundleName=%{public}s", name.c_str()); + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function OnProcess has already been released"); + return; + } + if (!bool(callbacks->onProcess)) { + HILOGI("callback function OnProcess is undefined"); + return; + } + auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { + napi_value napi_bName = nullptr; + napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); + argv.push_back(napi_bName); + napi_value napi_process = nullptr; + napi_create_string_utf8(env, process.c_str(), process.size(), &napi_res); + argv.push_back(napi_process); + return true; + }; + callbacks->onProcess.CallJsMethod(cbCompl); +} + napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Constructor begin"); @@ -274,7 +302,8 @@ napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info .onBundleFinished = bind(onBundleEnd, backupEntity->callbacks, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(onAllBundlesEnd, backupEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, backupEntity->callbacks, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks)}); + .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks), + .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2)}); if (!backupEntity->session) { NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init backup").GetCode()).ThrowErr(env); return nullptr; diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp index 8d386e094..4866c51a6 100644 --- a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -254,6 +254,34 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) callbacks->onBackupServiceDied.ThreadSafeSchedule(cbCompl); } +static void OnProcess(weak_ptr pCallbacks, const BundleName name, const std::string processInfo) +{ + HILOGI("Callback OnProcess, bundleName=%{public}s", name.c_str()); + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function OnProcess has already been released"); + return; + } + if (!bool(callbacks->onProcess)) { + HILOGI("callback function OnProcess is undefined"); + return; + } + auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { + napi_value napi_bName = nullptr; + napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); + argv.push_back(napi_bName); + napi_value napi_process = nullptr; + napi_create_string_utf8(env, process.c_str(), process.size(), &napi_res); + argv.push_back(napi_process); + return true; + }; + callbacks->onProcess.CallJsMethod(cbCompl); +} + napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Constructor begin"); @@ -281,7 +309,8 @@ napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_cal .onBundleFinished = bind(onBundleEnd, backupEntity->callbacks, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(onAllBundlesEnd, backupEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, backupEntity->callbacks, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks)}); + .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks), + .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2)}); if (!backupEntity->session) { NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init backup").GetCode()).ThrowErr(env); return nullptr; diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index 71d362b8d..737e37f76 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -260,6 +260,34 @@ static void OnResultReport(weak_ptr pCallbacks, const std::str callbacks->onResultReport.CallJsMethod(cbCompl); } +static void OnProcess(weak_ptr pCallbacks, const BundleName name, const std::string processInfo) +{ + HILOGI("Callback OnProcess, bundleName=%{public}s", name.c_str()); + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function OnProcess has already been released"); + return; + } + if (!bool(callbacks->onProcess)) { + HILOGI("callback function OnProcess is undefined"); + return; + } + auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { + napi_value napi_bName = nullptr; + napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); + argv.push_back(napi_bName); + napi_value napi_process = nullptr; + napi_create_string_utf8(env, process.c_str(), process.size(), &napi_res); + argv.push_back(napi_process); + return true; + }; + callbacks->onProcess.CallJsMethod(cbCompl); +} + static bool VerifyAppendBundlesParam(NFuncArg &funcArg, int32_t &fd, std::vector &bundleNames, std::vector &bundleInfos, napi_env env) { @@ -391,7 +419,8 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info .onBundleFinished = bind(onBundleEnd, restoreEntity->callbacks, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(onAllBundlesEnd, restoreEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, restoreEntity->callbacks, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks)}); + .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks), + .onProcess = bind(OnProcess, restoreEntity->callbacks, placeholders::_1, placeholders::_2)}); if (!restoreEntity->sessionSheet) { NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init restore").GetCode()).ThrowErr(env); return nullptr; diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index a3a7d7b0a..86771d371 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -77,6 +77,7 @@ public: ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) override; ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override; ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override; + ErrCode ReportBundleProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) override; ErrCode SAResultReport(const std::string bundleName, const std::string resultInfo, const ErrCode errCode, const BackupRestoreScenario sennario); diff --git a/services/backup_sa/include/module_ipc/service_reverse_proxy.h b/services/backup_sa/include/module_ipc/service_reverse_proxy.h index 43d4e13bb..3e6667d8d 100644 --- a/services/backup_sa/include/module_ipc/service_reverse_proxy.h +++ b/services/backup_sa/include/module_ipc/service_reverse_proxy.h @@ -27,6 +27,7 @@ public: void BackupOnResultReport(std::string result, std::string bundleName) override; void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void BackupOnAllBundlesFinished(int32_t errCode) override; + void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) override; @@ -34,6 +35,7 @@ public: ErrCode errCode = 0) override; void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; void RestoreOnAllBundlesFinished(int32_t errCode) override; + void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, @@ -41,6 +43,7 @@ public: void IncrementalBackupOnResultReport(std::string result, std::string bundleName) override; void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; + void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, @@ -49,6 +52,7 @@ public: ErrCode errCode = 0) override; void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) override; + void IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; public: explicit ServiceReverseProxy(const sptr &impl) : IRemoteProxy(impl) {} diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h index bd40fdd1e..2d6738ca8 100644 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ b/services/backup_sa/include/module_ipc/service_stub.h @@ -62,6 +62,7 @@ private: int32_t CmdGetBackupInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdUpdateTimer(MessageParcel &data, MessageParcel &reply); int32_t CmdUpdateSendRate(MessageParcel &data, MessageParcel &reply); + int32_t CmdReportBundleProcessInfo(MessageParcel &data, MessageParcel &reply); void ServiceStubSupplement(); void ServiceStubSuppAppendBundles(); diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index a896ceb52..21dcb8d7e 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -1708,4 +1708,30 @@ void Service::NotifyCallerCurAppDone(ErrCode errCode, const std::string &callerN session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, callerName); } } + +ErrCode Service::ReportBundleProcessInfo(const std::string processInfo, BackupRestoreScenario sennario) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + try { + string bundleName = VerifyCallerAndGetCallerName(); + if (sennario == BackupRestoreScenario::FULL_RESTORE) { + session_->GetServiceReverseProxy()->RestoreOnProcessInfo(bundleName, processInfo); + } else if (sennario == BackupRestoreScenario::INCREMENTAL_RESTORE) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnProcessInfo(bundleName, processInfo); + } else if (sennario == BackupRestoreScenario::FULL_BACKUP) { + session_->GetServiceReverseProxy()->BackupOnProcessInfo(bundleName, processInfo); + } else if (sennario == BackupRestoreScenario::INCREMENTAL_BACKUP) { + session_->GetServiceReverseProxy()->IncrementalBackupOnProcessInfo(bundleName, processInfo); + } + return BError(BError::Codes::OK); + } catch (const BError &e) { + return e.GetCode(); // 任意异常产生,终止监听该任务 + } catch (const exception &e) { + HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + return EPERM; + } catch (...) { + HILOGI("Unexpected exception"); + return EPERM; + } +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index bd6d1be91..9f93ca029 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -43,6 +43,9 @@ void ServiceStub::ServiceStubSupplement() opToInterfaceMap_[static_cast( IServiceInterfaceCode::SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP)] = &ServiceStub::CmdGetAppLocalListAndDoIncrementalBackup; + opToInterfaceMap_[static_cast( + IServiceInterfaceCode::SERVICE_CMD_REPORT_BUNDLE_PROCESS_INFO)] = + &ServiceStub::CmdReportBundleProcessInfo; } void ServiceStub::ServiceStubSuppAppendBundles() @@ -622,6 +625,19 @@ int32_t ServiceStub::CmdGetIncrementalFileHandle(MessageParcel &data, MessagePar return GetIncrementalFileHandle(bundleName, fileName); } +int32_t ServiceStub::CmdReportBundleProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + string processInfo; + if (!data.ReadString(processInfo)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleName").GetCode(); + } + BackupRestoreScenario secenrioInfo = static_cast(scenario); + if (!data.ReadInt32(errCode)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive errCode"); + } + return ReportBundleProcessInfo(processInfo, secenrioInfo); +} + template bool ServiceStub::ReadParcelableVector(std::vector &parcelableInfos, MessageParcel &data) { diff --git a/tools/backup_tool/src/tools_op_backup.cpp b/tools/backup_tool/src/tools_op_backup.cpp index fcf892a4b..966827301 100644 --- a/tools/backup_tool/src/tools_op_backup.cpp +++ b/tools/backup_tool/src/tools_op_backup.cpp @@ -189,6 +189,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, result = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void BackupToolDirSoftlinkToBackupDir() { // 判断BConstants::BACKUP_TOOL_LINK_DIR 是否是软链接 @@ -249,7 +254,8 @@ static int32_t InitPathCapFile(const string &pathCapFile, vector bundleN .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init backup\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_incremental_backup.cpp b/tools/backup_tool/src/tools_op_incremental_backup.cpp index 2be218c80..32312082d 100644 --- a/tools/backup_tool/src/tools_op_incremental_backup.cpp +++ b/tools/backup_tool/src/tools_op_incremental_backup.cpp @@ -224,6 +224,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string &bundleName, const std::string &processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void BackupToolDirSoftlinkToBackupDir() { // 判断BConstants::BACKUP_TOOL_LINK_DIR 是否是软链接 @@ -308,7 +313,8 @@ static int32_t Init(const string &pathCapFile, const vector& bundleNames .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init backup\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_incremental_restore.cpp b/tools/backup_tool/src/tools_op_incremental_restore.cpp index a713c3642..0e31f4a7a 100644 --- a/tools/backup_tool/src/tools_op_incremental_restore.cpp +++ b/tools/backup_tool/src/tools_op_incremental_restore.cpp @@ -219,6 +219,11 @@ static void OnResultReport(shared_ptr ctx, const std::string &bu printf("OnResultReport bundleName = %s, resultInfo = %s\n", bundleName.c_str(), resultInfo.c_str()); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void RestoreApp(shared_ptr restore) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); @@ -272,7 +277,8 @@ static int32_t InitRestoreSession(shared_ptr ctx, .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_incremental_restore_async.cpp b/tools/backup_tool/src/tools_op_incremental_restore_async.cpp index a2ff6d7d1..7acfa5897 100644 --- a/tools/backup_tool/src/tools_op_incremental_restore_async.cpp +++ b/tools/backup_tool/src/tools_op_incremental_restore_async.cpp @@ -246,6 +246,14 @@ static void OnResultReport(shared_ptr ctx, const std::st printf("OnResultReport bundleName = %s, resultInfo = %s\n", bundleName.c_str(), resultInfo.c_str()); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnResultReport bundleName = %s, result = %s\n", bundleName.c_str(), processInfo.c_str()); +} bundleName = %s, result = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void RestoreApp(shared_ptr restore, vector &bundleNames) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); @@ -402,7 +410,8 @@ static int32_t InitArg(const string &pathCapFile, .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_restore.cpp b/tools/backup_tool/src/tools_op_restore.cpp index e9c172426..bcf4075e8 100644 --- a/tools/backup_tool/src/tools_op_restore.cpp +++ b/tools/backup_tool/src/tools_op_restore.cpp @@ -197,6 +197,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void RestoreApp(shared_ptr restore, vector &bundleNames, bool updateSendFiles) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); @@ -257,7 +262,8 @@ static int32_t InitRestoreSession(shared_ptr ctx) .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_restore_async.cpp b/tools/backup_tool/src/tools_op_restore_async.cpp index a12a600f0..f97caf19e 100644 --- a/tools/backup_tool/src/tools_op_restore_async.cpp +++ b/tools/backup_tool/src/tools_op_restore_async.cpp @@ -170,6 +170,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static map> ReadyExtManage(const string &path, std::vector& pkgInfo) { @@ -385,7 +390,8 @@ static int32_t InitArg(const string &pathCapFile, .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index 512526b5c..6d4a9dbb8 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -77,6 +77,10 @@ constexpr int MIN_FD_SEND_RATE = 0; // 允许应用申请的最小FD数量 constexpr int DEFAULT_FD_SEND_RATE = 60; // 框架默认的FD数量 constexpr int32_t PARAM_STARING_MAX_MEMORY = 2 * 1024 * 1024; +constexpr int CALL_APP_ON_PROCESS_TIME_INTERVAL = 5000; // 框架每隔5s去调用应用的onProcess +constexpr int APP_ON_PROCESS_MAX_TIMEOUT = 1000; // 应用的onProcess接口最大超时时间为1秒 +constexpr int APP_ON_PROCESS_TIMEOUT_MAX_COUNT = 3; // 应用的onProcess接口超时的上限次数 + // backup.para内配置项的名称,该配置项值为true时可在不更新hap包的情况下,可以读取包管理元数据配置文件的内容 static inline std::string BACKUP_DEBUG_OVERRIDE_EXTENSION_CONFIG_KEY = "backup.debug.overrideExtensionConfig"; -- Gitee From b4bd6a53102f79625b334c6eaff16f226b928799 Mon Sep 17 00:00:00 2001 From: wangpggg Date: Tue, 13 Aug 2024 10:49:23 +0800 Subject: [PATCH 28/53] add ut to cover branches Signed-off-by: wangpeng --- .../backup_ext/ext_backup_js_test.cpp | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/tests/unittests/backup_ext/ext_backup_js_test.cpp b/tests/unittests/backup_ext/ext_backup_js_test.cpp index b4dce1570..bb76737d1 100644 --- a/tests/unittests/backup_ext/ext_backup_js_test.cpp +++ b/tests/unittests/backup_ext/ext_backup_js_test.cpp @@ -1282,4 +1282,153 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestoreEx_0200, testing::ext:: } GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestoreEx_0200"; } + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestore_0100 + * @tc.name: SUB_backup_ext_js_CallJSRestore_0100 + * @tc.desc: 测试 CallJSRestore 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestore_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestore_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestore."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestore_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestore_0200 + * @tc.name: SUB_backup_ext_js_CallJSRestore_0200 + * @tc.desc: 测试 CallJSRestore 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestore_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestore_0200"; + try { + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestore."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestore_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_GetBackupInfo_0100 + * @tc.name: SUB_backup_ext_js_GetBackupInfo_0100 + * @tc.desc: 测试 GetBackupInfo 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_GetBackupInfo_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_GetBackupInfo_0100"; + try { + extBackupJs->jsObj_ = make_unique(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_ok)) + .WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by GetBackupInfo."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_GetBackupInfo_0200"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From e07e9b8d76dcdeb17334e8b2a1d9ac14202dcbce Mon Sep 17 00:00:00 2001 From: chen0088 Date: Mon, 12 Aug 2024 20:00:20 +0800 Subject: [PATCH 29/53] ut Signed-off-by: chen0088 --- .../tools_op_incremental_restore_test.cpp | 220 +++++++++++++++++- .../b_json/b_report_entity_test.cpp | 120 ++++++++++ 2 files changed, 339 insertions(+), 1 deletion(-) diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp index 9d0847e42..94de50821 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp @@ -303,7 +303,7 @@ HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_ vector times; times.push_back("10"); times.push_back("20"); - int32_t ret = InitRestoreSession(nullptr, bundleNames, times); + int32_t ret = InitRestoreSession(ctx, bundleNames, times); EXPECT_EQ(0, ret); BFileInfo fileInfo; @@ -577,6 +577,41 @@ HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_ GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1002"; } +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1003 + * @tc.name: SUB_backup_tools_op_incremental_restore_1003 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1003"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("10"); + times.push_back("20"); + int32_t ret = InitRestoreSession(ctx, bundleNames, times); + EXPECT_EQ(0, ret); + + RestoreApp(ctx); + EXPECT_TRUE(ctx); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1003"; +} + /** * @tc.number: SUB_backup_tools_op_incremental_restore_1100 * @tc.name: SUB_backup_tools_op_incremental_restore_1100 @@ -628,4 +663,187 @@ HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_ } GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1101"; } + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1102 + * @tc.name: SUB_backup_tools_op_incremental_restore_1102 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1102"; + try { + string pathCapFile = ""; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = false; + vector times = {"10"}; + int32_t ret = Init(pathCapFile, bundleNames, depMode, times); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1102"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1200 + * @tc.name: SUB_backup_tools_op_incremental_restore_1200 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1200"; + try { + map> mapArgToVal; + mapArgToVal["depMode"] = {"false"}; + g_exec(mapArgToVal); + EXPECT_EQ(mapArgToVal["depMode"][0], "false"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1200"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1201 + * @tc.name: SUB_backup_tools_op_incremental_restore_1201 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1201, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1201"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1201"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1202 + * @tc.name: SUB_backup_tools_op_incremental_restore_1202 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1202, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1202"; + try { + map> mapArgToVal = { + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1202"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1203 + * @tc.name: SUB_backup_tools_op_incremental_restore_1203 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1203, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1203"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}}, + {"depMode", {"true"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1203"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1204 + * @tc.name: SUB_backup_tools_op_incremental_restore_1204 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1204, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1204"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1204"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1205 + * @tc.name: SUB_backup_tools_op_incremental_restore_1205 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1205, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1205"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1205"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp b/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp index 3e51ac258..cbdba7332 100644 --- a/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp +++ b/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp @@ -227,4 +227,124 @@ HWTEST_F(BReportEntityTest, b_report_entity_DealLine_0100, testing::ext::TestSiz GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_DealLine_0100"; } +/** + * @tc.number: SUB_backup_b_report_entity_DealLine_0101 + * @tc.name: b_report_entity_DealLine_0101 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_DealLine_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_DealLine_0101"; + try { + unordered_map keys; + int num = 1; + string line = ""; + unordered_map infos; + DealLine(keys, num, line, infos); + EXPECT_EQ(infos.size(), 0); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_DealLine_0101"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0100 + * @tc.name: b_report_entity_StorageDealLine_0100 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0100"; + try { + unordered_map keys; + int num = 1; + string line = ""; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0100"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0101 + * @tc.name: b_report_entity_StorageDealLine_0101 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0101"; + try { + unordered_map keys; + int num = 0; + string line = "test\r"; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0101"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0102 + * @tc.name: b_report_entity_StorageDealLine_0102 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0102"; + try { + unordered_map keys; + int num = 1; + string line = "key1;key2;key3"; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0102"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0103 + * @tc.name: b_report_entity_StorageDealLine_0103 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0103, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0103"; + try { + unordered_map keys; + int num = INFO_ALIGN_NUM; + string line = "key1;key2;key3"; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0103"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From afa5f6d1870d4deaf0bc34f9e2e68b8f3ddeabef Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Tue, 13 Aug 2024 11:46:38 +0800 Subject: [PATCH 30/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: Icb937be63f2682bfd211ee7f4b48c60c3c632efd --- test/unittest/file_share_ndk_test/BUILD.gn | 1 + .../file_share_nopermission_sup_test/BUILD.gn | 55 +++++ .../file_share_nopermission_sup_test.cpp | 218 ++++++++++++++++++ .../file_share_permission_sup_test.cpp | 190 +++++++++++++++ .../remote_file_share_test.cpp | 2 +- 5 files changed, 465 insertions(+), 1 deletion(-) create mode 100644 test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/BUILD.gn create mode 100644 test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/file_share_nopermission_sup_test.cpp diff --git a/test/unittest/file_share_ndk_test/BUILD.gn b/test/unittest/file_share_ndk_test/BUILD.gn index 8aa1a6eec..c4725a350 100644 --- a/test/unittest/file_share_ndk_test/BUILD.gn +++ b/test/unittest/file_share_ndk_test/BUILD.gn @@ -16,6 +16,7 @@ import("//build/test.gni") group("unittest") { testonly = true deps = [ + "file_share_nopermission_sup_test:file_share_no_permission_ndk_sup_test", "file_share_nopermission_test:file_share_no_permission_ndk_test", "file_share_permission_sup_test:file_share_permission_ndk_sup_test", "file_share_permission_test:file_share_permission_ndk_test", diff --git a/test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/BUILD.gn b/test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/BUILD.gn new file mode 100644 index 000000000..1ae89af21 --- /dev/null +++ b/test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") + +ohos_unittest("file_share_no_permission_ndk_sup_test") { + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${app_file_service_path}/cfi_blocklist.txt" + } + + module_out_path = "filemanagement/app_file_service" + include_dirs = [ + "include", + "${app_file_service_path}/interfaces/kits/ndk/fileshare/include", + "${app_file_service_path}/tests/mock/parameter_mock/include", + "//third_party/googletest/include", + ] + + sources = [ + "${app_file_service_path}/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp", + "${app_file_service_path}/tests/mock/parameter_mock/src/parameter_mock.cpp", + "file_share_nopermission_sup_test.cpp", + ] + external_deps = [ + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "file_api:filemgmt_libn", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + ] + + deps = [ + "${app_file_service_path}/interfaces/innerkits/native:fileshare_native", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] +} diff --git a/test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/file_share_nopermission_sup_test.cpp b/test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/file_share_nopermission_sup_test.cpp new file mode 100644 index 000000000..76fd55734 --- /dev/null +++ b/test/unittest/file_share_ndk_test/file_share_nopermission_sup_test/file_share_nopermission_sup_test.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include "securec.h" + +#include "common_func.h" +#include "error_code.h" +#include "oh_file_share.h" +#include "parameter_mock.h" + +using namespace testing::ext; +using namespace testing; +using namespace OHOS::AppFileService; +using namespace std; + +namespace OHOS::AppFileService::ModuleFileShareNoPermission { + +class NDKFileShareNoPermissionSupTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() {}; + void TearDown() {}; + static inline shared_ptr paramMoc_ = nullptr; +}; + +void NDKFileShareNoPermissionSupTest::SetUpTestCase() +{ + paramMoc_ = make_shared(); + ParamMoc::paramMoc = paramMoc_; +} + +void NDKFileShareNoPermissionSupTest::TearDownTestCase() +{ + ParamMoc::paramMoc = nullptr; + paramMoc_ = nullptr; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileShareNoPermissionSupTest, OH_FileShare_PersistPermission_test, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = { + .uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PERMISSION); + if (result != nullptr) { + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + } + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test end"; +} + +/** + * @tc.name: OH_FileShare_RevokePermission_test + * @tc.desc: Test function of OH_FileShare_RevokePermission() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileShareNoPermissionSupTest, OH_FileShare_RevokePermission_test, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PERMISSION); + if (result != nullptr) { + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + } + GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test end"; +} + +/** + * @tc.name: OH_FileShare_ActivatePermission_test + * @tc.desc: Test function of OH_FileShare_ActivatePermission() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileShareNoPermissionSupTest, OH_FileShare_ActivatePermission_test, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PERMISSION); + if (result != nullptr) { + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + } + GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test end"; +} + +/** + * @tc.name: OH_FileShare_DeactivatePermission_test + * @tc.desc: Test function of OH_FileShare_DeactivatePermission() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileShareNoPermissionSupTest, OH_FileShare_DeactivatePermission_test, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PERMISSION); + if (result != nullptr) { + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + } + GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileShareNoPermissionSupTest, OH_FileShare_CheckPersistentPermission_test, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PERMISSION); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test end"; +} + +} // namespace OHOS::AppFileService::ModuleFileShareNoPermission \ No newline at end of file diff --git a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp index 01a820ef4..38f66f1d9 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp @@ -255,4 +255,194 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_004, OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_004 end"; } + +/** + * @tc.name: OH_FileShare_PersistPermission_test_005 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_005 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)).WillOnce(Return(E_NO_ERROR)); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_NO_ERROR); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_005 end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test_001 + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_001 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(-1)); + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + + EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_001 end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test_002 + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_002 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = 0, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + if (result != nullptr) { + free(result); + } + + policies[0].length = strlen(policyUriChar); + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)).WillOnce(Return(EPERM)); + ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_002 end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test_003 + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_003 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)).WillOnce(Return(E_NO_ERROR)); + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + if (result != nullptr) { + free(result); + } + + std::vector errorResults; + for (int i = 0; i <= sizeof(FileShare_PolicyErrorResult) * MAX_ARRAY_SIZE; i++) { + errorResults.push_back(false); + } + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_NO_ERROR))); + ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_003 end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test_004 + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_004 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + //char value[] = "false"; + + std::vector errorResults; + errorResults.push_back(false); + + EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { + memcpy_s(value, sizeof("false"), "true", sizeof("true")); + })), Return(1))); + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_NO_ERROR))); + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_NO_ERROR); + + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_004 end"; +} } // namespace OHOS::AppFileService::ModuleFileSharePermission diff --git a/test/unittest/remote_file_share/remote_file_share_test.cpp b/test/unittest/remote_file_share/remote_file_share_test.cpp index 6d49e0d1d..e501bb704 100644 --- a/test/unittest/remote_file_share/remote_file_share_test.cpp +++ b/test/unittest/remote_file_share/remote_file_share_test.cpp @@ -438,7 +438,7 @@ namespace { HmdfsUriInfo hui; auto ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); - EXPECT_EQ(ret, 2); + EXPECT_NE(ret, 0); GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0013"; } -- Gitee From f73b593126c0708f95a7f552220ce6e2b773d714 Mon Sep 17 00:00:00 2001 From: cuiruibin Date: Tue, 13 Aug 2024 15:21:25 +0800 Subject: [PATCH 31/53] =?UTF-8?q?=E6=8C=81=E4=B9=85=E6=8E=88=E6=9D=83?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3NDK=E5=8F=96=E6=B6=88=E6=9D=83=E9=99=90?= =?UTF-8?q?=E5=92=8C=E8=AE=BE=E5=A4=87=E7=B1=BB=E5=9E=8B=E7=AE=A1=E6=8E=A7?= =?UTF-8?q?=20Signed-off-by:=20cuiruibin=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kits/ndk/fileshare/src/oh_file_share.cpp | 32 ------------------- 1 file changed, 32 deletions(-) diff --git a/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp b/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp index 53a0b7988..1b115fc1d 100644 --- a/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp +++ b/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp @@ -29,29 +29,9 @@ #include "tokenid_kit.h" const int32_t FOO_MAX_LEN = sizeof(FileShare_PolicyErrorResult) * OHOS::AppFileService::MAX_ARRAY_SIZE; -const std::string FILE_ACCESS_PERSIST_PERMISSION = "ohos.permission.FILE_ACCESS_PERSIST"; -const std::string FULL_MOUNT_ENABLE_PARAMETER = "const.filemanager.full_mount.enable"; using Exec = std::function &uriPolicies, std::deque &errorResults)>; -static bool CheckPermission(const std::string &permission) -{ - OHOS::Security::AccessToken::AccessTokenID tokenCaller = OHOS::IPCSkeleton::GetCallingTokenID(); - return OHOS::Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - OHOS::Security::AccessToken::PermissionState::PERMISSION_GRANTED; -} - -static bool CheckFileManagerFullMountEnable() -{ - char value[] = "false"; - int retSystem = GetParameter(FULL_MOUNT_ENABLE_PARAMETER.c_str(), "false", value, sizeof(value)); - if (retSystem > 0 && !strcmp(value, "true")) { - LOGI("The full mount enable parameter is true"); - return true; - } - LOGI("The full mount enable parameter is false"); - return false; -} static bool ConvertPolicyInfo(const FileShare_PolicyInfo *policies, int policyNum, @@ -173,12 +153,6 @@ static FileManagement_ErrCode ExecAction(const FileShare_PolicyInfo *policies, Exec exec) { (*resultNum) = 0; - if (!CheckFileManagerFullMountEnable()) { - return E_DEVICE_NOT_SUPPORT; - } - if (!CheckPermission(FILE_ACCESS_PERSIST_PERMISSION)) { - return E_PERMISSION; - } std::vector uriPolicies; if (!ConvertPolicyInfo(policies, policyNum, uriPolicies)) { return E_PARAMS; @@ -274,12 +248,6 @@ FileManagement_ErrCode OH_FileShare_CheckPersistentPermission(const FileShare_Po return E_PARAMS; } *resultNum = 0; - if (!CheckFileManagerFullMountEnable()) { - return E_DEVICE_NOT_SUPPORT; - } - if (!CheckPermission(FILE_ACCESS_PERSIST_PERMISSION)) { - return E_PERMISSION; - } std::vector uriPolicies; if (!ConvertPolicyInfo(policies, policyNum, uriPolicies)) { return E_PARAMS; -- Gitee From bb396df402fc190edfb201a1532486916aee8e76 Mon Sep 17 00:00:00 2001 From: libo429 Date: Tue, 13 Aug 2024 15:11:46 +0800 Subject: [PATCH 32/53] add clear data config Signed-off-by: libo429 --- .../native/backup_ext/include/ext_backup.h | 3 + .../native/backup_ext/include/ext_extension.h | 12 ++- .../native/backup_ext/src/ext_backup.cpp | 16 ++-- .../native/backup_ext/src/ext_extension.cpp | 76 +++++++++++++++---- .../backup_ext/src/ext_extension_stub.cpp | 12 ++- .../backup_kit_inner/impl/i_extension.h | 6 +- .../backup_sa/include/module_ipc/service.h | 3 +- .../include/module_ipc/svc_extension_proxy.h | 6 +- .../include/module_ipc/svc_session_manager.h | 4 + services/backup_sa/src/module_ipc/service.cpp | 29 ++++--- .../src/module_ipc/service_incremental.cpp | 16 ++-- .../svc_extension_incremental_proxy.cpp | 6 +- .../src/module_ipc/svc_extension_proxy.cpp | 12 ++- .../src/module_ipc/svc_session_manager.cpp | 20 +++++ .../module_ipc/svc_extension_proxy_mock.cpp | 6 +- .../module_ipc/svc_session_manager_mock.cpp | 7 ++ .../svc_session_manager_throw_mock.cpp | 10 +++ .../svc_session_manager_throw_mock.h | 4 + .../backup_impl/include/ext_extension_mock.h | 6 +- .../backup_ext/ext_extension_stub_test.cpp | 18 ++--- .../module_ipc/svc_extension_proxy_test.cpp | 12 ++- .../b_jsonutil/b_jsonutil_test.cpp | 54 +++++++++---- utils/include/b_jsonutil/b_jsonutil.h | 15 ++-- utils/src/b_jsonutil/b_jsonutil.cpp | 25 ++++-- 24 files changed, 275 insertions(+), 103 deletions(-) diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h index dae003248..b4d902bc9 100644 --- a/frameworks/native/backup_ext/include/ext_backup.h +++ b/frameworks/native/backup_ext/include/ext_backup.h @@ -170,6 +170,8 @@ public: */ bool RestoreDataReady(); + void SetClearDataFlag(bool isClearData); + /** * @brief Invoke the extended function of the APP */ @@ -195,6 +197,7 @@ private: BConstants::ExtensionAction extAction_ {BConstants::ExtensionAction::INVALID}; ErrCode GetParament(const AAFwk::Want &want); static CreatorFunc creator_; + bool isClearData_ {true}; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index b93bdbb3e..513f25070 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -43,12 +43,12 @@ public: UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) override; ErrCode HandleClear() override; ErrCode PublishFile(const std::string &fileName) override; - ErrCode HandleBackup() override; - ErrCode HandleRestore() override; + ErrCode HandleBackup(bool isClearData) override; + ErrCode HandleRestore(bool isClearData) override; ErrCode GetIncrementalFileHandle(const std::string &fileName) override; ErrCode PublishIncrementalFile(const std::string &fileName) override; ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; - ErrCode IncrementalOnBackup() override; + ErrCode IncrementalOnBackup(bool isClearData) override; std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; @@ -194,6 +194,11 @@ private: std::function AppDoneCallbackEx(wptr obj); std::function HandleBackupEx(wptr obj); std::function HandleTaskBackupEx(wptr obj); + void HandleSpecialVersionRestore(wptr obj); + void DeleteBackupIncrementalTars(); + void DeleteBackupTars(); + void SetClearDataFlag(bool isClearData); + private: std::shared_mutex lock_; std::shared_ptr extension_; @@ -207,6 +212,7 @@ private: std::mutex waitTimeLock_; std::string bundleName_; int32_t sendRate_ = BConstants::DEFAULT_FD_SEND_RATE; + bool isClearData_ {true}; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index 280518596..1a4bc1f78 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -189,12 +189,6 @@ sptr ExtBackup::OnConnect(const AAFwk::Want &want) auto remoteObject = sptr(new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); - - // 排除特殊场景 - if (!WasFromSpecialVersion() && !RestoreDataReady()) { - remoteObject->ExtClear(); - } - return remoteObject->AsObject(); } catch (const BError &e) { return nullptr; @@ -211,6 +205,11 @@ void ExtBackup::OnDisconnect(const AAFwk::Want &want) { try { HILOGI("begin disconnect"); + if (isClearData_) { + auto remoteObject = sptr( + new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); + remoteObject->ExtClear(); + } Extension::OnDisconnect(want); extAction_ = BConstants::ExtensionAction::INVALID; HILOGI("end"); @@ -253,6 +252,11 @@ bool ExtBackup::RestoreDataReady() return restoreType_ == RestoreTypeEnum::RESTORE_DATA_READDY; } +void ExtBackup::SetClearDataFlag(bool isClearData) +{ + isClearData_ = isClearData; +} + ErrCode ExtBackup::OnBackup(function callback) { HILOGI("BackupExtensionAbility(base) OnBackup."); diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 723d18df1..bf8bdde80 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -466,9 +466,10 @@ ErrCode BackupExtExtension::PublishIncrementalFile(const string &fileName) } } -ErrCode BackupExtExtension::HandleBackup() +ErrCode BackupExtExtension::HandleBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + SetClearDataFlag(isClearData); if (extension_ == nullptr) { HILOGE("Failed to handle backup, extension is nullptr"); return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); @@ -872,8 +873,12 @@ static void RestoreBigFiles(bool appendTargetPath) HILOGI("End Restore Big Files"); } -static void DeleteBackupTars() +void BackupExtExtension::DeleteBackupTars() { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); if (fd < 0) { @@ -901,8 +906,12 @@ static void DeleteBackupTars() HILOGI("End execute DeleteBackupTars"); } -static void DeleteBackupIncrementalTars() +void BackupExtExtension::DeleteBackupIncrementalTars() { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); @@ -937,6 +946,19 @@ static void DeleteBackupIncrementalTars() } } +void BackupExtExtension::HandleSpecialVersionRestore(wptr obj) +{ + auto ptr = obj.promote(); + BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); + auto ret = RestoreFilesForSpecialCloneCloud(); + if (ret == ERR_OK) { + ptr->AsyncTaskRestoreForUpgrade(); + } else { + ptr->AppDone(ret); + ptr->DoClear(); + } +} + void BackupExtExtension::AsyncTaskRestore(std::set fileSet, const std::vector extManageInfo) { @@ -947,13 +969,7 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, try { int ret = ERR_OK; if (ptr->extension_->SpecialVersionForCloneAndCloud()) { - ret = RestoreFilesForSpecialCloneCloud(); - if (ret == ERR_OK) { - ptr->AsyncTaskRestoreForUpgrade(); - } else { - ptr->AppDone(ret); - ptr->DoClear(); - } + ptr->HandleSpecialVersionRestore(obj); return; } // 解压 @@ -967,7 +983,7 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, bool appendTargetPath = ptr->extension_->UseFullBackupOnly() && !ptr->extension_->SpecialVersionForCloneAndCloud(); RestoreBigFiles(appendTargetPath); - DeleteBackupTars(); + ptr->DeleteBackupTars(); if (ret == ERR_OK) { ptr->AsyncTaskRestoreForUpgrade(); } else { @@ -1012,7 +1028,7 @@ void BackupExtExtension::AsyncTaskIncrementalRestore() RestoreBigFiles(appendTargetPath); // delete 1.tar/manage.json - DeleteBackupIncrementalTars(); + ptr->DeleteBackupIncrementalTars(); if (ret == ERR_OK) { HILOGI("after extra, do incremental restore."); @@ -1198,6 +1214,10 @@ void BackupExtExtension::DoClear() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } string backupCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); string restoreCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); @@ -1224,7 +1244,11 @@ void BackupExtExtension::AppDone(ErrCode errCode) HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("AppDone Begin."); auto proxy = ServiceProxy::GetInstance(); - BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + if (proxy == nullptr) { + HILOGE("Failed to obtain the ServiceProxy handle"); + DoClear(); + return; + } auto ret = proxy->AppDone(errCode); if (ret != ERR_OK) { HILOGE("Failed to notify the app done. err = %{public}d", ret); @@ -1290,10 +1314,11 @@ void BackupExtExtension::AsyncTaskOnBackup() }); } -ErrCode BackupExtExtension::HandleRestore() +ErrCode BackupExtExtension::HandleRestore(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); VerifyCaller(); + SetClearDataFlag(isClearData); if (extension_ == nullptr) { HILOGE("Failed to handle restore, extension is nullptr"); throw BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr"); @@ -1415,9 +1440,10 @@ ErrCode BackupExtExtension::HandleIncrementalBackup(UniqueFd incrementalFd, Uniq return 0; } -ErrCode BackupExtExtension::IncrementalOnBackup() +ErrCode BackupExtExtension::IncrementalOnBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + SetClearDataFlag(isClearData); if (extension_ == nullptr) { HILOGE("Failed to handle incremental onBackup, extension is nullptr"); return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); @@ -1799,7 +1825,11 @@ void BackupExtExtension::AppIncrementalDone(ErrCode errCode) { HILOGI("Begin"); auto proxy = ServiceProxy::GetInstance(); - BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + if (proxy == nullptr) { + HILOGE("Failed to obtain the ServiceProxy handle"); + DoClear(); + return; + } auto ret = proxy->AppIncrementalDone(errCode); if (ret != ERR_OK) { HILOGE("Failed to notify the app done. err = %{public}d", ret); @@ -2015,4 +2045,18 @@ void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point & fdSendNum = 0; } } + +void BackupExtExtension::SetClearDataFlag(bool isClearData) +{ + isClearData_ = isClearData; + HILOGI("set clear data flag:%{public}d", isClearData); + if (extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extension_->SetClearDataFlag(isClearData); + if (!extension_->WasFromSpecialVersion() && !extension_->RestoreDataReady()) { + DoClear(); + } +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension_stub.cpp b/frameworks/native/backup_ext/src/ext_extension_stub.cpp index 6930c2982..1589df3b4 100644 --- a/frameworks/native/backup_ext/src/ext_extension_stub.cpp +++ b/frameworks/native/backup_ext/src/ext_extension_stub.cpp @@ -106,7 +106,9 @@ ErrCode ExtExtensionStub::CmdHandleClear(MessageParcel &data, MessageParcel &rep ErrCode ExtExtensionStub::CmdHandleBackup(MessageParcel &data, MessageParcel &reply) { - ErrCode res = HandleBackup(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = HandleBackup(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -133,7 +135,9 @@ ErrCode ExtExtensionStub::CmdPublishFile(MessageParcel &data, MessageParcel &rep ErrCode ExtExtensionStub::CmdHandleRestore(MessageParcel &data, MessageParcel &reply) { - ErrCode res = HandleRestore(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = HandleRestore(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -187,7 +191,9 @@ ErrCode ExtExtensionStub::CmdHandleIncrementalBackup(MessageParcel &data, Messag ErrCode ExtExtensionStub::CmdIncrementalOnBackup(MessageParcel &data, MessageParcel &reply) { - ErrCode res = IncrementalOnBackup(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = IncrementalOnBackup(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h index 364214d2d..387ec3b0e 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h @@ -30,13 +30,13 @@ public: virtual ~IExtension() = default; virtual UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) = 0; virtual ErrCode HandleClear() = 0; - virtual ErrCode HandleBackup() = 0; + virtual ErrCode HandleBackup(bool isClearData) = 0; virtual ErrCode PublishFile(const std::string &fileName) = 0; - virtual ErrCode HandleRestore() = 0; + virtual ErrCode HandleRestore(bool isClearData) = 0; virtual ErrCode GetIncrementalFileHandle(const std::string &fileName) = 0; virtual ErrCode PublishIncrementalFile(const std::string &fileName) = 0; virtual ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) = 0; - virtual ErrCode IncrementalOnBackup() = 0; + virtual ErrCode IncrementalOnBackup(bool isClearData) = 0; virtual std::tuple GetIncrementalBackupFileHandle() = 0; virtual ErrCode GetBackupInfo(std::string &result) = 0; virtual ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) = 0; diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index a3a7d7b0a..45a9393e5 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -318,12 +318,13 @@ private: * @param restoreBundleInfos 待恢复的应用 * @param restoreBundleNames 待恢复的应用包信息 * @param bundleNameDetailMap bundle和detail的对应关系 + * @param isClearDataFlags 清理数据标志集合 * @param restoreType 任务类型 */ void SetCurrentSessProperties(std::vector &restoreBundleInfos, std::vector &restoreBundleNames, std::map> &bundleNameDetailMap, - RestoreTypeEnum restoreType); + std::map &isClearDataFlags, RestoreTypeEnum restoreType); /** * @brief set session info diff --git a/services/backup_sa/include/module_ipc/svc_extension_proxy.h b/services/backup_sa/include/module_ipc/svc_extension_proxy.h index e817810ae..a20ef5112 100644 --- a/services/backup_sa/include/module_ipc/svc_extension_proxy.h +++ b/services/backup_sa/include/module_ipc/svc_extension_proxy.h @@ -25,13 +25,13 @@ class SvcExtensionProxy : public IRemoteProxy { public: UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) override; ErrCode HandleClear() override; - ErrCode HandleBackup() override; + ErrCode HandleBackup(bool isClearData) override; ErrCode PublishFile(const std::string &fileName) override; - ErrCode HandleRestore() override; + ErrCode HandleRestore(bool isClearData) override; ErrCode GetIncrementalFileHandle(const std::string &fileName) override; ErrCode PublishIncrementalFile(const std::string &fileName) override; ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; - ErrCode IncrementalOnBackup() override; + ErrCode IncrementalOnBackup(bool isClearData) override; std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h index bdb674fed..7baf1cabb 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -66,6 +66,7 @@ struct BackupExtInfo { int32_t backupPriority; std::string extInfo; int32_t appendNum {1}; + bool isClearData {true}; }; class Service; @@ -478,6 +479,9 @@ public: Impl GetImpl(); int GetSessionCnt(); + void SetClearDataFlag(const std::string &bundleName, bool isClearData); + bool GetClearDataFlag(const std::string &bundleName); + private: /** * @brief 获取backup extension ability diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index dc7b90a9f..e16760096 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -401,8 +401,9 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId, isClearDataFlags); auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); @@ -412,7 +413,8 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vectorAppendBundles(restoreBundleNames); - SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, + isClearDataFlags, restoreType); OnStartSched(); session_->DecreaseSessionCnt(); HILOGI("End"); @@ -497,7 +499,8 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, void Service::SetCurrentSessProperties(std::vector &restoreBundleInfos, std::vector &restoreBundleNames, - std::map> &bundleNameDetailMap, RestoreTypeEnum restoreType) + std::map> &bundleNameDetailMap, + std::map &isClearDataFlags, RestoreTypeEnum restoreType) { HILOGI("Start"); for (auto restoreInfo : restoreBundleInfos) { @@ -524,6 +527,10 @@ void Service::SetCurrentSessProperties(std::vector session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName); session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied); session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName); + auto iter = isClearDataFlags.find(bundleNameIndexInfo); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(bundleNameIndexInfo, iter->second); + } BJsonUtil::BundleDetailInfo broadCastInfo; BJsonUtil::BundleDetailInfo uniCastInfo; bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE, @@ -589,22 +596,26 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); std::vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, session_->GetSessionUserId()); + BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + session_->GetSessionUserId(), isClearDataFlags); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { session_->SetBundleDataSize(info.name, info.spaceOccupied); session_->SetBackupExtName(info.name, info.extensionName); + auto iter = isClearDataFlags.find(info.name); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(info.name, iter->second); + } if (info.allToBackup == false) { session_->GetServiceReverseProxy()->BackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); session_->RemoveExtInfo(info.name); } BJsonUtil::BundleDetailInfo uniCastInfo; - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, - uniCastInfo); - if (uniCastRet) { + if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, uniCastInfo)) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); session_->SetBackupExtInfo(info.name, uniCastInfo.detail); } @@ -1042,7 +1053,7 @@ void Service::ExtStart(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "ExtStart bundle task error, Extension backup Proxy is empty"); } if (scenario == IServiceReverse::Scenario::BACKUP) { - auto ret = proxy->HandleBackup(); + auto ret = proxy->HandleBackup(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); if (ret) { ClearSessionAndSchedInfo(bundleName); @@ -1053,7 +1064,7 @@ void Service::ExtStart(const string &bundleName) if (scenario != IServiceReverse::Scenario::RESTORE) { throw BError(BError::Codes::SA_INVAL_ARG, "Failed to scenario"); } - auto ret = proxy->HandleRestore(); + auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); for (auto &fileName : fileNameVec) { diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index 07c6f6f87..7df256035 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -293,22 +293,26 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, infos, bundleNamesOnly, session_->GetSessionUserId()); + BJsonUtil::BuildBundleInfos(bundleNames, infos, bundleNamesOnly, + session_->GetSessionUserId(), isClearDataFlags); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { session_->SetBundleDataSize(info.name, info.spaceOccupied); session_->SetBackupExtName(info.name, info.extensionName); + auto iter = isClearDataFlags.find(info.name); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(info.name, iter->second); + } if (info.allToBackup == false) { session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); session_->RemoveExtInfo(info.name); } BJsonUtil::BundleDetailInfo uniCastInfo; - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, - uniCastInfo); - if (uniCastRet) { + if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, uniCastInfo)) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); session_->SetBackupExtInfo(info.name, uniCastInfo.detail); } @@ -519,7 +523,7 @@ bool Service::IncrementalBackup(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { - auto ret = proxy->IncrementalOnBackup(); + auto ret = proxy->IncrementalOnBackup(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(ret, bundleName); if (ret) { ClearSessionAndSchedInfo(bundleName); @@ -528,7 +532,7 @@ bool Service::IncrementalBackup(const string &bundleName) return true; } else if (scenario == IServiceReverse::Scenario::RESTORE && BackupPara().GetBackupOverrideIncrementalRestore() && session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) { - auto ret = proxy->HandleRestore(); + auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(ret, bundleName); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); for (auto &fileName : fileNameVec) { diff --git a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp index c4355e6aa..434ac777c 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp @@ -101,13 +101,15 @@ ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, Uniqu return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::IncrementalOnBackup() +ErrCode SvcExtensionProxy::IncrementalOnBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGD("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; diff --git a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp index 57e126eb3..ce2bfcc36 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp @@ -79,13 +79,15 @@ ErrCode SvcExtensionProxy::HandleClear() return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::HandleBackup() +ErrCode SvcExtensionProxy::HandleBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; @@ -126,13 +128,15 @@ ErrCode SvcExtensionProxy::PublishFile(const string &fileName) return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::HandleRestore() +ErrCode SvcExtensionProxy::HandleRestore(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index f62b1ae2c..20bb48b24 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -847,6 +847,26 @@ void SvcSessionManager::SetMemParaCurSize(int32_t size) memoryParaCurSize_ = size; } +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isClearData) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + it->second.isClearData = isClearData; + HILOGI("bundleName:%{public}s, set clear data flag:%{public}d.", bundleName.c_str(), isClearData); +} +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + return it->second.isClearData; +} + bool SvcSessionManager::ValidRestoreDataType(RestoreTypeEnum restoreDataType) { return impl_.restoreDataType == restoreDataType; diff --git a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp index bd20c461f..c7032836b 100644 --- a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp +++ b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp @@ -28,7 +28,7 @@ ErrCode SvcExtensionProxy::HandleClear() return 0; } -ErrCode SvcExtensionProxy::HandleBackup() +ErrCode SvcExtensionProxy::HandleBackup(bool isClearData) { return 0; } @@ -38,7 +38,7 @@ ErrCode SvcExtensionProxy::PublishFile(const string &fileName) return 0; } -ErrCode SvcExtensionProxy::HandleRestore() +ErrCode SvcExtensionProxy::HandleRestore(bool isClearData) { return 0; } @@ -63,7 +63,7 @@ ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, Uniqu return 0; } -ErrCode SvcExtensionProxy::IncrementalOnBackup() +ErrCode SvcExtensionProxy::IncrementalOnBackup(bool isClearData) { return 0; } diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index eff1d65e0..53b97b777 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -399,6 +399,13 @@ int SvcSessionManager::GetSessionCnt() return sessionCnt_.load(); } +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isNotClear) {} + +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + return true; +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) {} int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName) diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp index de45882f4..80acd08fc 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -280,6 +280,16 @@ int SvcSessionManager::GetSessionCnt() return BackupSvcSessionManager::session->GetSessionCnt(); } +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isNotClear) +{ + BackupSvcSessionManager::session->SetClearDataFlag(bundleName, isNotClear); +} + +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + return BackupSvcSessionManager::session->GetClearDataFlag(bundleName); +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) { BackupSvcSessionManager::session->SetIncrementalData(incrementalData); diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.h b/tests/mock/module_ipc/svc_session_manager_throw_mock.h index 633488906..f00d6e93d 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -79,6 +79,8 @@ public: virtual bool ValidRestoreDataType(RestoreTypeEnum) = 0; virtual SvcSessionManager::Impl GetImpl() = 0; virtual int GetSessionCnt() = 0; + virtual void SetClearDataFlag(const std::string &bundleName, bool isNotClear) = 0; + virtual bool GetClearDataFlag(const std::string &bundleName) = 0; virtual void SetIncrementalData(const BIncrementalData &) = 0; virtual int32_t GetIncrementalManifestFd(const std::string &) = 0; virtual int64_t GetLastIncrementalTime(const std::string &) = 0; @@ -140,6 +142,8 @@ public: MOCK_METHOD(bool, ValidRestoreDataType, (RestoreTypeEnum)); MOCK_METHOD(SvcSessionManager::Impl, GetImpl, ()); MOCK_METHOD(int, GetSessionCnt, ()); + MOCK_METHOD(void, SetClearDataFlag, (const std::string &, bool)); + MOCK_METHOD(bool, GetClearDataFlag, (const std::string &)); MOCK_METHOD(void, SetIncrementalData, (const BIncrementalData &)); MOCK_METHOD(int32_t, GetIncrementalManifestFd, (const std::string &)); MOCK_METHOD(int64_t, GetLastIncrementalTime, (const std::string &)); diff --git a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h index 7484d1b8c..6ff7362e0 100644 --- a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h @@ -79,7 +79,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode HandleBackup() override + ErrCode HandleBackup(bool isClearData) override { GTEST_LOG_(INFO) << "HandleBackup"; if (nHandleBackupNum_ == 1) { @@ -99,7 +99,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode HandleRestore() override + ErrCode HandleRestore(bool isClearData) override { return BError(BError::Codes::OK); }; @@ -119,7 +119,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode IncrementalOnBackup() override + ErrCode IncrementalOnBackup(bool isClearData) override { return BError(BError::Codes::OK); }; diff --git a/tests/unittests/backup_ext/ext_extension_stub_test.cpp b/tests/unittests/backup_ext/ext_extension_stub_test.cpp index 413212265..ba73c7db6 100644 --- a/tests/unittests/backup_ext/ext_extension_stub_test.cpp +++ b/tests/unittests/backup_ext/ext_extension_stub_test.cpp @@ -28,13 +28,13 @@ class ExtExtensionStubMock : public ExtExtensionStub { public: MOCK_METHOD(UniqueFd, GetFileHandle, (const std::string &fileName, int32_t &errCode)); MOCK_METHOD(ErrCode, HandleClear, ()); - MOCK_METHOD(ErrCode, HandleBackup, ()); + MOCK_METHOD(ErrCode, HandleBackup, (bool isClearData)); MOCK_METHOD(ErrCode, PublishFile, (const std::string &fileName)); - MOCK_METHOD(ErrCode, HandleRestore, ()); + MOCK_METHOD(ErrCode, HandleRestore, (bool isClearData)); MOCK_METHOD(ErrCode, GetIncrementalFileHandle, (const std::string &fileName)); MOCK_METHOD(ErrCode, PublishIncrementalFile, (const std::string &fileName)); MOCK_METHOD(ErrCode, HandleIncrementalBackup, (UniqueFd incrementalFd, UniqueFd manifestFd)); - MOCK_METHOD(ErrCode, IncrementalOnBackup, ()); + MOCK_METHOD(ErrCode, IncrementalOnBackup, (bool isClearData)); MOCK_METHOD((std::tuple), GetIncrementalBackupFileHandle, ()); MOCK_METHOD(ErrCode, GetBackupInfo, (std::string &result)); MOCK_METHOD(ErrCode, UpdateFdSendRate, (std::string &bundleName, int32_t sendRate)); @@ -201,13 +201,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdHandleBackup_0 try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, HandleBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdHandleBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, HandleBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdHandleBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); @@ -271,13 +271,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdHandleRestore_ try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, HandleRestore()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleRestore(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdHandleRestore(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, HandleRestore()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleRestore(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdHandleRestore(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); @@ -417,13 +417,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdIncrementalOnB try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, IncrementalOnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, IncrementalOnBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdIncrementalOnBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, IncrementalOnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, IncrementalOnBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdIncrementalOnBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); diff --git a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp index 0e54994bf..23df5b143 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp @@ -148,15 +148,17 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleBackup_0100, testi GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleBackup_0100"; try { EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); EXPECT_TRUE(proxy_ != nullptr); - ErrCode ret = proxy_->HandleBackup(); + ErrCode ret = proxy_->HandleBackup(true); EXPECT_EQ(EPERM, ret); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock_, ReadInt32()).WillOnce(Return(0)); - ret = proxy_->HandleBackup(); + ret = proxy_->HandleBackup(true); EXPECT_EQ(BError(BError::Codes::OK), ret); } catch (...) { EXPECT_TRUE(false); @@ -218,15 +220,17 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleRestore_0100, test GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleRestore_0100"; try { EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); EXPECT_TRUE(proxy_ != nullptr); - ErrCode ret = proxy_->HandleRestore(); + ErrCode ret = proxy_->HandleRestore(true); EXPECT_EQ(EPERM, ret); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock_, ReadInt32()).WillOnce(Return(0)); - ret = proxy_->HandleRestore(); + ret = proxy_->HandleRestore(true); EXPECT_EQ(BError(BError::Codes::OK), ret); } catch (...) { EXPECT_TRUE(false); diff --git a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp index 1d0c9727f..f1536a851 100644 --- a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp +++ b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp @@ -111,7 +111,9 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0100, testing::ext::TestSize bundleInfos.push_back(bundleInfo2); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_TRUE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -141,7 +143,9 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0200, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -171,7 +175,9 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0300, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_TRUE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -201,7 +207,9 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0301, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_TRUE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -227,12 +235,16 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0400, testing::ext::TestSize std::string bundleName = "bundle1"; bundleNames.push_back(bundleName); std::vector bundleInfos; - std::string bundleInfo = {"{\"infos\":[{\"type\":\"type1\",\"details\":\"details1\"}]}"}; + std::string bundleInfo = { + "{\"infos\":[{\"type\":\"type1\",\"details\":\"details1\"}],\"clearBackupData\": \"false\"}" + }; bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; - - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_EQ(isClearDataFlags[bundleName], false); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -262,8 +274,11 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0500, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; + std::map isClearDataFlags; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_EQ(isClearDataFlags[bundleName], true); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -289,12 +304,15 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0600, testing::ext::TestSize std::string bundleName = "bundle"; bundleNames.push_back(bundleName); std::vector bundleInfos; - std::string bundleInfo = {"{\"infos\":[{\"type\":123}]}"}; + std::string bundleInfo = {"{\"infos\":[{\"type\":123}],\"clearBackupData\": \"true\"}"}; bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; + std::map isClearDataFlags; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_EQ(isClearDataFlags[bundleName], true); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -324,8 +342,10 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0700, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; + std::map isClearDataFlags; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -355,8 +375,10 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0800, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; + std::map isClearDataFlags; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -386,8 +408,10 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0900, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; + std::map isClearDataFlags; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); @@ -417,8 +441,10 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_1000, testing::ext::TestSize bundleInfos.push_back(bundleInfo); int32_t userId = TEST_USER_ID; std::vector bundleNamesOnly; + std::map isClearDataFlags; - auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); EXPECT_FALSE(result.empty()); } catch (...) { EXPECT_TRUE(false); diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index 8799488df..e3e729ca2 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -47,26 +47,27 @@ public: * @param patternInfo 拼接的字符 * @param realBundleNames 分割后真正的bundleNames * @param userId userId + * @param isClearDataFlags 框架是否清理标志集合 * * @return 包名和解析结果的对应关系集合 * */ static std::map> BuildBundleInfos( const std::vector &bundleNames, const std::vector &details, - std::vector &realBundleNames, int32_t userId); + std::vector &realBundleNames, int32_t userId, + std::map &isClearDataFlags); /** * @brief 解析单个bundle对应的json串 * - * @param bundleDetailInfo json串 - * @param bundleDetail 结构体对象 - * @param bundleNameOnly bundle名称 - * @param bundleIndex bundle对应的索引 - * @param userId userId + * @param bundleInfo json串 + * @param bundleDetails 结构体对象 + * @param bundleDetailInfo bundle信息 + * @param isClearData 框架是否清理标志 * */ static void ParseBundleInfoJson(const std::string &bundleInfo, std::vector &bundleDetails, - std::string &bundleNameOnly, int bundleIndex, int32_t userId); + BJsonUtil::BundleDetailInfo bundleDetailInfo, bool &isClearData); /** * @brief 根据业务类型和bundleName确定唯一的bundleInfo diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index 53fdb36e8..b50042c1c 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -49,7 +49,8 @@ BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string std::map> BJsonUtil::BuildBundleInfos( const std::vector &bundleNames, const std::vector &bundleInfos, - std::vector &bundleNamesOnly, int32_t userId) + std::vector &bundleNamesOnly, int32_t userId, + std::map &isClearDataFlags) { std::map> bundleNameDetailMap; if (bundleNames.size() != bundleInfos.size()) { @@ -80,7 +81,13 @@ std::map> BJsonUtil::Build bundleNamesOnly.emplace_back(bundleNameSplit); } std::string bundleInfo = bundleInfos[i]; - ParseBundleInfoJson(bundleInfo, bundleDetailInfos, bundleNameOnly, bundleIndex, userId); + bool isClearData = true; + BJsonUtil::BundleDetailInfo bundleDetailInfo; + bundleDetailInfo.bundleName = bundleNameOnly; + bundleDetailInfo.bundleIndex = bundleIndex; + bundleDetailInfo.userId = userId; + ParseBundleInfoJson(bundleInfo, bundleDetailInfos, bundleDetailInfo, isClearData); + isClearDataFlags[bundleName] = isClearData; bundleNameDetailMap[bundleName] = bundleDetailInfos; } HILOGI("End BuildBundleInfos"); @@ -88,13 +95,21 @@ std::map> BJsonUtil::Build } void BJsonUtil::ParseBundleInfoJson(const std::string &bundleInfo, std::vector &bundleDetails, - std::string &bundleNameOnly, int bundleIndex, int32_t userId) + BJsonUtil::BundleDetailInfo bundleDetailInfo, bool &isClearData) { cJSON *root = cJSON_Parse(bundleInfo.c_str()); if (root == nullptr) { HILOGE("Parse json error,root is null"); return; } + cJSON *clearBackupData = cJSON_GetObjectItem(root, "clearBackupData"); + if (clearBackupData == nullptr || !cJSON_IsString(clearBackupData) || (clearBackupData->valuestring == nullptr)) { + HILOGE("Parse json error."); + } else { + std::string value = clearBackupData->valuestring; + isClearData = value.compare("false") != 0; + HILOGI("bundleName:%{public}s clear data falg:%{public}d", bundleDetailInfo.bundleName.c_str(), isClearData); + } cJSON *infos = cJSON_GetObjectItem(root, "infos"); if (infos == nullptr || !cJSON_IsArray(infos) || cJSON_GetArraySize(infos) == 0) { HILOGE("Parse json error, infos is not array"); @@ -103,10 +118,6 @@ void BJsonUtil::ParseBundleInfoJson(const std::string &bundleInfo, std::vector Date: Tue, 13 Aug 2024 16:34:38 +0800 Subject: [PATCH 33/53] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=88=86=E8=BA=AB?= =?UTF-8?q?=E6=97=B6=E7=9A=84=E5=8C=85=E5=90=8D=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yaoruozi1@huawei.com --- .../backup_sa/src/module_ipc/svc_restore_deps_manager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp index 5907c0ecc..682b0a2b4 100644 --- a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp @@ -29,9 +29,9 @@ vector SvcRestoreDepsManager::GetRestoreBundleNames(const vector Date: Mon, 12 Aug 2024 16:41:25 +0800 Subject: [PATCH 34/53] fix errCode --- .../kits/js/backup/prop_n_operation.cpp | 46 ++--- .../js/backup/session_backup_n_exporter.cpp | 30 ++++ .../session_incremental_backup_n_exporter.cpp | 31 ++++ .../js/backup/session_restore_n_exporter.cpp | 157 +++++++++++++----- services/backup_sa/BUILD.gn | 1 + services/backup_sa/src/module_ipc/service.cpp | 40 +++-- .../src/module_sched/sched_scheduler.cpp | 2 +- .../mock/accesstoken/accesstoken_kit_mock.cpp | 6 + utils/BUILD.gn | 3 + utils/include/b_error/b_error.h | 18 +- utils/include/b_sa/b_sa_utils.h | 3 + utils/src/b_error/b_error.cpp | 1 + utils/src/b_sa/b_sa_utils.cpp | 28 ++++ 13 files changed, 290 insertions(+), 76 deletions(-) diff --git a/interfaces/kits/js/backup/prop_n_operation.cpp b/interfaces/kits/js/backup/prop_n_operation.cpp index d059dc95f..593c67a59 100644 --- a/interfaces/kits/js/backup/prop_n_operation.cpp +++ b/interfaces/kits/js/backup/prop_n_operation.cpp @@ -17,6 +17,7 @@ #include "b_error/b_error.h" #include "b_incremental_data.h" #include "b_resources/b_constants.h" +#include "b_sa/b_sa_utils.h" #include "filemgmt_libhilog.h" #include "filemgmt_libn.h" #include "incremental_backup_data.h" @@ -32,19 +33,6 @@ using namespace LibN; const int32_t H_TO_MS = 3600 * 1000; -static bool CheckPermission(const string &permission) -{ - Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - Security::AccessToken::PermissionState::PERMISSION_GRANTED; -} - -static bool IsSystemApp() -{ - uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); - return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); -} - static napi_value AsyncCallback(napi_env env, const NFuncArg& funcArg) { HILOGD("called LocalCapabilities::AsyncCallback begin"); @@ -182,6 +170,16 @@ static napi_value AsyncDataList(napi_env env, const NFuncArg& funcArg) napi_value PropNOperation::Async(napi_env env, napi_callback_info info) { HILOGD("called LocalCapabilities::Async begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched."); @@ -203,6 +201,16 @@ napi_value PropNOperation::Async(napi_env env, napi_callback_info info) napi_value PropNOperation::DoGetBackupInfo(napi_env env, napi_callback_info info) { HILOGD("called DoGetBackupInfo begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::string result; NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { @@ -278,12 +286,12 @@ bool PropNOperation::UpdateSendRate(std::string &bundleName, int32_t sendRate) napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) { HILOGD("called DoUpdateTimer begin"); - if (!CheckPermission("ohos.permission.BACKUP")) { - HILOGE("has not permission!"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); NError(E_PERMISSION).ThrowErr(env); return nullptr; } - if (!IsSystemApp()) { + if (!SAUtils::IsSystemApp()) { HILOGE("System App check fail!"); NError(E_PERMISSION_SYS).ThrowErr(env); return nullptr; @@ -326,12 +334,12 @@ napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) napi_value PropNOperation::DoUpdateSendRate(napi_env env, napi_callback_info info) { HILOGD("called DoUpdateSendRate begin"); - if (!CheckPermission("ohos.permission.BACKUP")) { - HILOGE("has not permission!"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); NError(E_PERMISSION).ThrowErr(env); return nullptr; } - if (!IsSystemApp()) { + if (!SAUtils::IsSystemApp()) { HILOGE("System App check fail!"); NError(E_PERMISSION_SYS).ThrowErr(env); return nullptr; diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_backup_n_exporter.cpp index 0d84c0308..3198e00c8 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_backup_n_exporter.cpp @@ -251,6 +251,16 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched."); @@ -326,6 +336,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector &bund napi_value SessionBackupNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::vector bundleNames; std::vector bundleInfos; NFuncArg funcArg(env, cbinfo); @@ -369,6 +389,16 @@ napi_value SessionBackupNExporter::AppendBundles(napi_env env, napi_callback_inf napi_value SessionBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp index 8d386e094..69bfc1768 100644 --- a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -22,6 +22,7 @@ #include "b_incremental_backup_session.h" #include "b_incremental_data.h" #include "b_resources/b_constants.h" +#include "b_sa/b_sa_utils.h" #include "backup_kit_inner.h" #include "directory_ex.h" #include "filemgmt_libhilog.h" @@ -257,6 +258,16 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched"); @@ -391,6 +402,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector napi_value SessionIncrementalBackupNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::vector backupBundles; std::vector bundleInfos; NFuncArg funcArg(env, cbinfo); @@ -431,6 +452,16 @@ napi_value SessionIncrementalBackupNExporter::AppendBundles(napi_env env, napi_c napi_value SessionIncrementalBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index 71d362b8d..dd3ccf163 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -371,6 +371,16 @@ static bool VerifyNarg(napi_env env, NVal &callbacks) napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGI("called SessionRestore::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (VerifyNapiObject(env, funcArg)) { return nullptr; @@ -405,23 +415,16 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info return funcArg.GetThisVar(); } -napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) +static NContextCBExec GetAppendBundlesCBExec(napi_env env, NFuncArg &funcArg, const int32_t fdRestore, + const std::vector &bundleNames, const std::vector &bundleInfos) { - HILOGI("called SessionRestore::AppendBundles begin"); - int32_t fdRestore = BConstants::INVALID_FD_NUM; - std::vector bundleNames; - std::vector bundleInfos; - NFuncArg funcArg(env, cbinfo); - if (!VerifyAppendBundlesParam(funcArg, fdRestore, bundleNames, bundleInfos, env)) { - return nullptr; - } auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); return nullptr; } - auto cbExec = [entity {restoreEntity}, fd {fdRestore}, bundles {bundleNames}, infos {bundleInfos}]() -> NError { + return [entity {restoreEntity}, fd {fdRestore}, bundles {bundleNames}, infos {bundleInfos}]() -> NError { if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } @@ -440,10 +443,38 @@ napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_in } return NError(entity->sessionSheet->AppendBundles(UniqueFd(fd), bundles)); }; +} + +napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionRestore::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } + int32_t fdRestore = BConstants::INVALID_FD_NUM; + std::vector bundleNames; + std::vector bundleInfos; + NFuncArg funcArg(env, cbinfo); + if (!VerifyAppendBundlesParam(funcArg, fdRestore, bundleNames, bundleInfos, env)) { + return nullptr; + } + auto cbExec = GetAppendBundlesCBExec(env, funcArg, fdRestore, bundleNames, bundleInfos); + if (cbExec == nullptr) { + HILOGE("GetAppendBundlesCBExec fail!"); + return nullptr; + } auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; HILOGD("Called SessionRestore::AppendBundles end."); + NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::TWO) { return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; @@ -457,24 +488,16 @@ napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_in } } -napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info cbinfo) +static NContextCBExec GetPublishFileCBExec(napi_env env, NFuncArg &funcArg, const std::string &bundleName, + const std::string &fileName) { - HILOGD("called SessionRestore::PublishFile begin"); - std::string bundleName; - std::string fileName; - NFuncArg funcArg(env, cbinfo); - if (!VerifyPublishFileParam(funcArg, bundleName, fileName, env)) { - return nullptr; - } - auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); return nullptr; } - - auto cbExec = [entity {restoreEntity}, bundleName {bundleName}, fileName {fileName}]() -> NError { + return [entity {restoreEntity}, bundleName {bundleName}, fileName {fileName}]() -> NError { if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } @@ -492,10 +515,35 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info } return NError(entity->sessionSheet->PublishFile(fileInfo)); }; +} + +napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info cbinfo) +{ + HILOGD("called SessionRestore::PublishFile begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } + std::string bundleName; + std::string fileName; + NFuncArg funcArg(env, cbinfo); + if (!VerifyPublishFileParam(funcArg, bundleName, fileName, env)) { + return nullptr; + } + auto cbExec = GetPublishFileCBExec(env, funcArg, bundleName, fileName); + if (cbExec == nullptr) { + HILOGE("GetPublishFileCBExec fail!"); + return nullptr; + } auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGD("Called SessionRestore::PublishFile end."); NVal thisVar(env, funcArg.GetThisVar()); @@ -507,9 +555,42 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info } } +static NContextCBExec GetFileHandleCBExec(napi_env env, NFuncArg &funcArg, std::unique_ptr bundleName, + std::unique_ptr fileName) +{ + auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { + HILOGE("Failed to get RestoreSession entity."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); + return nullptr; + } + return [entity {restoreEntity}, bundleName {string(bundleName.get())}, + fileName {string(fileName.get())}]() -> NError { + if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); + } + string bundle = bundleName; + string file = fileName; + if (entity->sessionWhole) { + return NError(entity->sessionWhole->GetFileHandle(bundle, file)); + } + return NError(entity->sessionSheet->GetFileHandle(bundle, file)); + }; +} + napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionRestore::GetFileHandle begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { HILOGE("Number of arguments unmatched."); @@ -531,29 +612,14 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in return nullptr; } - auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { - HILOGE("Failed to get RestoreSession entity."); - NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); + auto cbExec = GetFileHandleCBExec(env, funcArg, move(bundleName), move(fileName)); + if (cbExec == nullptr) { + HILOGE("GetFileHandleCBExec fail!"); return nullptr; } - - auto cbExec = [entity {restoreEntity}, bundleName {string(bundleName.get())}, - fileName {string(fileName.get())}]() -> NError { - if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { - return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); - } - string bundle = bundleName; - string file = fileName; - if (entity->sessionWhole) { - return NError(entity->sessionWhole->GetFileHandle(bundle, file)); - } - return NError(entity->sessionSheet->GetFileHandle(bundle, file)); - }; auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGD("Called SessionRestore::GetFileHandle end."); NVal thisVar(env, funcArg.GetThisVar()); @@ -568,6 +634,16 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in napi_value SessionRestoreNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGI("called SessionRestore::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); @@ -594,7 +670,6 @@ napi_value SessionRestoreNExporter::Release(napi_env env, napi_callback_info cbi auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGI("Called SessionRestore::Release end."); NVal thisVar(env, funcArg.GetThisVar()); diff --git a/services/backup_sa/BUILD.gn b/services/backup_sa/BUILD.gn index 5bf8af4f0..027216afe 100644 --- a/services/backup_sa/BUILD.gn +++ b/services/backup_sa/BUILD.gn @@ -66,6 +66,7 @@ ohos_shared_library("backup_sa") { "ability_runtime:ability_connect_callback_stub", "ability_runtime:ability_manager", "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index dc7b90a9f..bc70e2ce5 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -54,6 +54,8 @@ #include "hisysevent.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" +#include "access_token.h" +#include "tokenid_kit.h" #include "module_app_gallery/app_gallery_dispose_proxy.h" #include "module_external/bms_adapter.h" #include "module_external/sms_adapter.h" @@ -80,6 +82,7 @@ const int32_t CONNECT_WAIT_TIME_S = 15; const std::string BACKUPSERVICE_WORK_STATUS_KEY = "persist.backupservice.workstatus"; const std::string BACKUPSERVICE_WORK_STATUS_ON = "true"; const std::string BACKUPSERVICE_WORK_STATUS_OFF = "false"; +const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP"; } // namespace /* Shell/Xts user id equal to 0/1, we need set default 100 */ @@ -219,23 +222,34 @@ void Service::VerifyCaller() uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); switch (tokenType) { - case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: /* Update Service */ + case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: { /* Update Service */ + if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != + Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); + } + break; + } case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: { - const string permission = "ohos.permission.BACKUP"; - if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - Security::AccessToken::TypePermissionState::PERMISSION_DENIED) { - throw BError(BError::Codes::SA_INVAL_ARG, - string("Permission denied, token type is ").append(to_string(tokenType))); + if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != + Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); + } + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) { + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); } break; } case Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL: if (IPCSkeleton::GetCallingUid() != BConstants::SYSTEM_UID) { - throw BError(BError::Codes::SA_INVAL_ARG, "Calling uid is invalid"); + throw BError(BError::Codes::SA_REFUSED_ACT, "Calling uid is invalid"); } break; default: - throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType))); + throw BError(BError::Codes::SA_REFUSED_ACT, string("Invalid token type ").append(to_string(tokenType))); break; } } @@ -880,7 +894,11 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) return BError(BError::Codes::SA_INVAL_ARG); } ErrCode ret = backUpConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); - return ret; + if (ret) { + HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + return BError(BError::Codes::SA_BOOT_EXT_FAIL); + } + return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); } catch (const exception &e) { @@ -1481,8 +1499,8 @@ ErrCode Service::GetBackupInfoCmdHandle(BundleName &bundleName, std::string &res AAFwk::Want want = CreateConnectWant(bundleName); auto ret = backupConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); if (ret) { - HILOGE("ConnectBackupExtAbility faild, please check bundleName: %{public}s", bundleName.c_str()); - return BError(BError::Codes::EXT_ABILITY_DIED); + HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + return BError(BError::Codes::SA_BOOT_EXT_FAIL); } std::unique_lock lock(getBackupInfoMutx_); getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S)); diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp index 910b1e4f7..20f7e530c 100644 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ b/services/backup_sa/src/module_sched/sched_scheduler.cpp @@ -83,7 +83,7 @@ void SchedScheduler::ExecutingQueueTasks(const string &bundleName) HILOGE("Extension connect failed = %{public}s", bundleName.data()); auto ptr = reversePtr.promote(); if (ptr) { - ptr->ExtConnectFailed(bundleName, BError(BError::Codes::SA_BOOT_TIMEOUT)); + ptr->ExtConnectFailed(bundleName, BError(BError::Codes::SA_BOOT_EXT_TIMEOUT)); } }; auto iTime = extTime_.Register(callStart, BConstants::EXT_CONNECT_MAX_TIME, true); diff --git a/tests/mock/accesstoken/accesstoken_kit_mock.cpp b/tests/mock/accesstoken/accesstoken_kit_mock.cpp index 153183770..f2c5795cc 100644 --- a/tests/mock/accesstoken/accesstoken_kit_mock.cpp +++ b/tests/mock/accesstoken/accesstoken_kit_mock.cpp @@ -14,6 +14,7 @@ */ #include "accesstoken_kit.h" +#include "tokenid_kit.h" namespace OHOS::Security::AccessToken { ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) @@ -31,4 +32,9 @@ int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string & { return 0; } + +bool TokenIdKit::IsSystemAppByFullTokenID(uint64_t tokenId) +{ + return true; +} } // namespace OHOS::Security::AccessToken diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 632b98ae1..151ab2480 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -83,12 +83,15 @@ ohos_shared_library("backup_utils") { public_configs = [ ":utils_public_config" ] external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "cJSON:cjson", "c_utils:utils", "faultloggerd:libdfx_dumpcatcher", "hilog:libhilog", "hitrace:hitrace_meter", "init:libbegetutil", + "ipc:ipc_core", ] include_dirs = [ diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h index 02bd0440e..8e84877d2 100644 --- a/utils/include/b_error/b_error.h +++ b/utils/include/b_error/b_error.h @@ -70,8 +70,9 @@ public: SA_REFUSED_ACT = 0x3002, SA_BROKEN_ROOT_DIR = 0x3003, SA_FORBID_BACKUP_RESTORE = 0x3004, - SA_BOOT_TIMEOUT = 0x3005, + SA_BOOT_EXT_TIMEOUT = 0x3005, SA_BUNDLE_INFO_EMPTY = 0x3006, + SA_BOOT_EXT_FAIL = 0x3007, // 0x4000~0x4999 backup_SDK错误 SDK_INVAL_ARG = 0x4000, @@ -89,6 +90,7 @@ public: EXT_BACKUP_PACKET_ERROR = 0x5007, EXT_METHOD_NOT_EXIST = 0x5008, EXT_THROW_EXCEPTION = 0x5009, + EXT_BACKUP_UNPACKET_ERROR = 0x5010, // 0x6000~0x6999 sa_ext错误 SA_EXT_ERR_CALL = 0x6000, @@ -112,6 +114,8 @@ public: E_EMPTY = 13500005, E_PACKET = 13500006, E_EXCEPTION = 13500007, + E_UNPACKET = 13500008, + E_BEF = 13500009, }; public: @@ -227,8 +231,9 @@ private: {Codes::SA_REFUSED_ACT, "SA refuse to act"}, {Codes::SA_BROKEN_ROOT_DIR, "SA failed to operate on the given root dir"}, {Codes::SA_FORBID_BACKUP_RESTORE, "SA forbid backup or restore"}, - {Codes::SA_BOOT_TIMEOUT, "SA boot application extension time out"}, + {Codes::SA_BOOT_EXT_TIMEOUT, "SA boot application extension time out"}, {Codes::SA_BUNDLE_INFO_EMPTY, "SA the bundle info for backup/restore is empty"}, + {Codes::SA_BOOT_EXT_FAIL, "SA failed to boot application extension"}, {Codes::SDK_INVAL_ARG, "SDK received invalid arguments"}, {Codes::SDK_BROKEN_IPC, "SDK failed to do IPC"}, {Codes::SDK_MIXED_SCENARIO, "SDK involed backup/restore when doing the contrary"}, @@ -241,6 +246,7 @@ private: {Codes::EXT_FORBID_BACKUP_RESTORE, "forbid backup or restore"}, {Codes::EXT_BACKUP_PACKET_ERROR, "Backup packet error"}, {Codes::EXT_THROW_EXCEPTION, "Extension throw exception"}, + {Codes::EXT_BACKUP_UNPACKET_ERROR, "Backup unpacket error"}, }; static inline const std::map errCodeTable_ { @@ -256,8 +262,9 @@ private: {static_cast(Codes::SA_REFUSED_ACT), BackupErrorCode::E_PERM}, {static_cast(Codes::SA_BROKEN_ROOT_DIR), BackupErrorCode::E_UKERR}, {static_cast(Codes::SA_FORBID_BACKUP_RESTORE), BackupErrorCode::E_FORBID}, - {static_cast(Codes::SA_BOOT_TIMEOUT), BackupErrorCode::E_BTO}, + {static_cast(Codes::SA_BOOT_EXT_TIMEOUT), BackupErrorCode::E_BTO}, {static_cast(Codes::SA_BUNDLE_INFO_EMPTY), BackupErrorCode::E_EMPTY}, + {static_cast(Codes::SA_BOOT_EXT_FAIL), BackupErrorCode::E_BEF}, {static_cast(Codes::SDK_INVAL_ARG), BackupErrorCode::E_INVAL}, {static_cast(Codes::SDK_BROKEN_IPC), BackupErrorCode::E_IPCSS}, {static_cast(Codes::SDK_MIXED_SCENARIO), BackupErrorCode::E_INVAL}, @@ -270,6 +277,7 @@ private: {static_cast(Codes::EXT_FORBID_BACKUP_RESTORE), BackupErrorCode::E_FORBID}, {static_cast(Codes::EXT_BACKUP_PACKET_ERROR), BackupErrorCode::E_PACKET}, {static_cast(Codes::EXT_THROW_EXCEPTION), BackupErrorCode::E_EXCEPTION}, + {static_cast(Codes::EXT_BACKUP_UNPACKET_ERROR), BackupErrorCode::E_UNPACKET}, {BackupErrorCode::E_IPCSS, BackupErrorCode::E_IPCSS}, {BackupErrorCode::E_INVAL, BackupErrorCode::E_INVAL}, {BackupErrorCode::E_NOTEXIST, BackupErrorCode::E_NOTEXIST}, @@ -285,10 +293,12 @@ private: {BackupErrorCode::E_EMPTY, BackupErrorCode::E_EMPTY}, {BackupErrorCode::E_PACKET, BackupErrorCode::E_PACKET}, {BackupErrorCode::E_EXCEPTION, BackupErrorCode::E_EXCEPTION}, + {BackupErrorCode::E_UNPACKET, BackupErrorCode::E_UNPACKET}, + {BackupErrorCode::E_BEF, BackupErrorCode::E_BEF}, }; static inline const std::map sysErrnoCodeTable_ { - {EPERM, BackupErrorCode::E_IPCSS}, + {EPERM, BackupErrorCode::E_PERM}, {EIO, BackupErrorCode::E_IO}, {EBADF, BackupErrorCode::E_IO}, {EACCES, BackupErrorCode::E_IO}, diff --git a/utils/include/b_sa/b_sa_utils.h b/utils/include/b_sa/b_sa_utils.h index 1548fed1e..86d1b8aa9 100644 --- a/utils/include/b_sa/b_sa_utils.h +++ b/utils/include/b_sa/b_sa_utils.h @@ -21,6 +21,9 @@ namespace OHOS::FileManagement::Backup { class SAUtils { public: static bool IsSABundleName(std::string bundleName); + static bool CheckBackupPermission(); + static bool CheckPermission(const std::string &permission); + static bool IsSystemApp(); }; } // namespace OHOS::FileManagement::Backup::BEncryption #endif // OHOS_FILEMGMT_BACKUP_B_SA_H \ No newline at end of file diff --git a/utils/src/b_error/b_error.cpp b/utils/src/b_error/b_error.cpp index d99d3e62e..5d13b4ec6 100644 --- a/utils/src/b_error/b_error.cpp +++ b/utils/src/b_error/b_error.cpp @@ -52,6 +52,7 @@ string BError::WrapMessageWithExtraInfos(const char *fileName, (void)HILOG_IMPL(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, LOG_TAG, "%{public}s", res.c_str()); return res; } + int BError::GetCode() const { int code = static_cast(GetRawCode()); diff --git a/utils/src/b_sa/b_sa_utils.cpp b/utils/src/b_sa/b_sa_utils.cpp index 05d090e81..399cb1026 100644 --- a/utils/src/b_sa/b_sa_utils.cpp +++ b/utils/src/b_sa/b_sa_utils.cpp @@ -14,9 +14,17 @@ */ #include "b_sa/b_sa_utils.h" +#include "access_token.h" +#include "accesstoken_kit.h" +#include "ipc_skeleton.h" +#include "tokenid_kit.h" namespace OHOS::FileManagement::Backup { +namespace { + const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP"; +} + bool SAUtils::IsSABundleName(std::string bundleName) { if (bundleName.empty()) { @@ -29,4 +37,24 @@ bool SAUtils::IsSABundleName(std::string bundleName) } return true; } + +bool SAUtils::CheckBackupPermission() +{ + Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) == + Security::AccessToken::PermissionState::PERMISSION_GRANTED; +} + +bool SAUtils::CheckPermission(const std::string &permission) +{ + Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == + Security::AccessToken::PermissionState::PERMISSION_GRANTED; +} + +bool SAUtils::IsSystemApp() +{ + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From c1c095430eedcaeaddd37066ddddedf547ba63dc Mon Sep 17 00:00:00 2001 From: zhonglufu Date: Tue, 13 Aug 2024 20:36:43 +0800 Subject: [PATCH 35/53] =?UTF-8?q?=E8=A1=A5=E5=85=85UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhonglufu --- .../backup_impl/service_proxy_test.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp index f95584e61..5e8506a7c 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -271,6 +271,36 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppDone_0100, testing::ext::TestSiz GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppDone_0100"; } +/** + * @tc.number: SUB_Service_proxy_ServiceResultReport_0100 + * @tc.name: SUB_Service_proxy_ServiceResultReport_0100 + * @tc.desc: 测试 ServiceResultReport + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_ServiceResultReport_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_ServiceResultReport_0100"; + if (proxy_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_Service_proxy_ServiceResultReport_0100 proxy_ == nullptr"; + return; + } + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + std::string restoreRetInfo = "test_restoreRetInfo"; + BackupRestoreScenario scenario = FULL_BACKUP; + int32_t result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); + EXPECT_EQ(result, BError(BError::Codes::OK)); + + result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); + EXPECT_NE(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_ServiceResultReport_0100"; +} + /** * @tc.number: SUB_Service_proxy_GetFileHandle_0100 * @tc.name: SUB_Service_proxy_GetFileHandle_0100 @@ -394,6 +424,37 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppendBundlesBackupSession_0100, te GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppendBundlesBackupSession_0100"; } +/** + * @tc.number: SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100 + * @tc.name: SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100 + * @tc.desc: 测试 AppendBundlesDetailsBackupSession + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6URNZ + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100"; + if (proxy_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100 proxy_ == nullptr"; + return; + } + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + + std::vector bundleNames; + std::vector detailInfos; + + int32_t result = proxy_->AppendBundlesDetailsBackupSession(bundleNames, detailInfos); + EXPECT_EQ(result, BError(BError::Codes::OK)); + result = proxy_->AppendBundlesDetailsBackupSession(bundleNames, detailInfos); + EXPECT_NE(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100"; +} + /** * @tc.number: SUB_Service_proxy_Finish_0100 * @tc.name: SUB_Service_proxy_Finish_0100 -- Gitee From e83fdd9a379ea51897e694100f6369dbc4e86b50 Mon Sep 17 00:00:00 2001 From: 17333770736 Date: Tue, 13 Aug 2024 20:41:34 +0800 Subject: [PATCH 36/53] =?UTF-8?q?=E8=A1=A5=E5=85=85UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 17333770736 --- tests/unittests/backup_api/backup_impl/service_proxy_test.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp index 5e8506a7c..9befd1d89 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -295,7 +295,6 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_ServiceResultReport_0100, testing:: BackupRestoreScenario scenario = FULL_BACKUP; int32_t result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); EXPECT_EQ(result, BError(BError::Codes::OK)); - result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); EXPECT_NE(result, BError(BError::Codes::OK)); GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_ServiceResultReport_0100"; -- Gitee From bea8a683f588a298634582fbcbbdfab841e912b7 Mon Sep 17 00:00:00 2001 From: 17333770736 Date: Tue, 13 Aug 2024 20:42:30 +0800 Subject: [PATCH 37/53] =?UTF-8?q?=E8=A1=A5=E5=85=85UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 17333770736 --- tests/unittests/backup_api/backup_impl/service_proxy_test.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp index 9befd1d89..b93201d1a 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -295,6 +295,7 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_ServiceResultReport_0100, testing:: BackupRestoreScenario scenario = FULL_BACKUP; int32_t result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); EXPECT_EQ(result, BError(BError::Codes::OK)); + result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); EXPECT_NE(result, BError(BError::Codes::OK)); GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_ServiceResultReport_0100"; @@ -449,6 +450,7 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppendBundlesDetailsBackupSession_0 int32_t result = proxy_->AppendBundlesDetailsBackupSession(bundleNames, detailInfos); EXPECT_EQ(result, BError(BError::Codes::OK)); + result = proxy_->AppendBundlesDetailsBackupSession(bundleNames, detailInfos); EXPECT_NE(result, BError(BError::Codes::OK)); GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100"; -- Gitee From 1a8a5f80f55d73641b0477bf100420293607a957 Mon Sep 17 00:00:00 2001 From: zhonglufu Date: Tue, 13 Aug 2024 21:39:16 +0800 Subject: [PATCH 38/53] =?UTF-8?q?AFS=20UT=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhonglufu --- .../backup_sa/module_ipc/service_test.cpp | 795 ++++++++++++++++++ 1 file changed, 795 insertions(+) diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index f2e6511c8..4c281d8ce 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -523,6 +523,46 @@ HWTEST_F(ServiceTest, SUB_Service_GetFileHandle_0100, testing::ext::TestSize.Lev GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetFileHandle_0100"; } +/** + * @tc.number: SUB_Service_GetFileHandle_0101 + * @tc.name: SUB_Service_GetFileHandle_0101 + * @tc.desc: 测试 GetFileHandle 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_GetFileHandle_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetFileHandle_0101"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + string bundleNameIndexInfo = "123456"; + extInfo.backUpConnection(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.schedAction = BConstants::ServiceSchedAction::RUNNING; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + extInfo.backUpConnection->backupProxy_ = nullptr; + EXPECT_TRUE(servicePtr_ != nullptr); + ret = servicePtr_->GetFileHandle(BUNDLE_NAME, FILE_NAME); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG)); + + extInfo.backUpConnection->backupProxy_(new IExtension()); + ret = servicePtr_->GetFileHandle(BUNDLE_NAME, FILE_NAME); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetFileHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetFileHandle_0101"; +} + /** * @tc.number: SUB_Service_OnBackupExtensionDied_0100 * @tc.name: SUB_Service_OnBackupExtensionDied_0100 @@ -554,6 +594,48 @@ HWTEST_F(ServiceTest, SUB_Service_OnBackupExtensionDied_0100, testing::ext::Test GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBackupExtensionDied_0100"; } +/** + * @tc.number: SUB_Service_OnBackupExtensionDied_0101 + * @tc.name: SUB_Service_OnBackupExtensionDied_0101 + * @tc.desc: 测试 OnBackupExtensionDied 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_OnBackupExtensionDied_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnBackupExtensionDied_0101"; + try { + GTEST_LOG_(INFO) << "SUB_Service_OnBackupExtensionDied_0101 RESTORE"; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + string bundleName = BUNDLE_NAME; + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + extInfo.backUpConnection = nullptr; + extInfo.versionName = "0.0.0.0-0.0.0.0"; + impl_.restoreDataType = RESTORE_DATA_WAIT_SEND; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->OnBackupExtensionDied(move(bundleName)); + GTEST_LOG_(INFO) << "SUB_Service_OnBackupExtensionDied_0101 BACKUP"; + + ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + impl_.restoreDataType = RESTORE_DATA_READDY; + bundleName = "123456789"; + impl_.backupExtNameMap[bundleName] = extInfo; + servicePtr_->OnBackupExtensionDied(move(bundleName)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetFileHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBackupExtensionDied_0101"; +} + /** * @tc.number: SUB_Service_ExtStart_0100 * @tc.name: SUB_Service_ExtStart_0100 @@ -584,6 +666,60 @@ HWTEST_F(ServiceTest, SUB_Service_ExtStart_0100, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtStart_0100"; } +/** + * @tc.number: SUB_Service_ExtStart_0101 + * @tc.name: SUB_Service_ExtStart_0101 + * @tc.desc: 测试 ExtStart 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_ExtStart_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ExtStart_0101"; + try { + GTEST_LOG_(INFO) << "SUB_Service_ExtStart_0101 BACKUP"; + std::string bundleName = "123456"; + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->ExtStart(bundleName); + + GTEST_LOG_(INFO) << "SUB_Service_ExtStart_0101 RESTORE"; + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + string bundleNameIndexInfo = "123456789"; + extInfo.backUpConnection(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.backUpConnection->backupProxy_ = nullptr; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::UNDEFINED; + ret = Init(IServiceReverse::Scenario::UNDEFINED); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtStart(BUNDLE_NAME); + + extInfo.backUpConnection->backupProxy_(new IExtension()); + ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtStart(BUNDLE_NAME); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtStart(BUNDLE_NAME); + + ret = Init(IServiceReverse::Scenario::UNDEFINED); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtStart(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtStart."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtStart_0101"; +} + /** * @tc.number: SUB_Service_Dump_0100 * @tc.name: SUB_Service_Dump_0100 @@ -678,6 +814,13 @@ HWTEST_F(ServiceTest, SUB_Service_ExtConnectFailed_0100, testing::ext::TestSize. ret = Init(IServiceReverse::Scenario::BACKUP); EXPECT_EQ(ret, BError(BError::Codes::OK)); servicePtr_->ExtConnectFailed(BUNDLE_NAME, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + impl_.restoreDataType = RESTORE_DATA_READDY; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtConnectFailed(BUNDLE_NAME, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtConnectFailed."; @@ -939,10 +1082,662 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0100, testing::ext::TestSize.Level uint32_t timeOut = 30000; EXPECT_TRUE(servicePtr_ != nullptr); servicePtr_->UpdateTimer(bundleName, timeOut, result); + EXPECT_EQ(ret, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UpdateTimer."; } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UpdateTimer_0100"; } + +/** + * @tc.number: SUB_Service_SpecialVersion_0100 + * @tc.name: SUB_Service_SpecialVersion_0100 + * @tc.desc: 测试 SpecialVersion 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SpecialVersion_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SpecialVersion_0100"; + try { + std::string versionName = "0.0.0.0-0.0.0.0"; + EXPECT_TRUE(servicePtr_ != nullptr); + bool ret = servicePtr_->SpecialVersion(versionName); + EXPECT_EQ(ret, true); + versionName = "1.1.1.1-1.1.1.1"; + bool ret = servicePtr_->SpecialVersion(versionName); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SpecialVersion."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SpecialVersion_0100"; +} + +/** + * @tc.number: SUB_Service_OnBundleStarted_0100 + * @tc.name: SUB_Service_OnBundleStarted_0100 + * @tc.desc: 测试 OnBundleStarted 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_OnBundleStarted_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnBundleStarted_0100"; + try { + int32_t saID = 2503; + wptr reversePtr(new Service(saID)); + sptr session(new SvcSessionManager(reversePtr)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + servicePtr_->OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by OnBundleStarted."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBundleStarted_0100"; +} + +/** + * @tc.number: SUB_Service_HandleExceptionOnAppendBundles_0100 + * @tc.name: SUB_Service_HandleExceptionOnAppendBundles_0100 + * @tc.desc: 测试 HandleExceptionOnAppendBundles 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_HandleExceptionOnAppendBundles_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_HandleExceptionOnAppendBundles_0100"; + try { + int32_t saID = 4801; + wptr reversePtr(new Service(saID)); + sptr session(new SvcSessionManager(reversePtr)); + vector appendBundleNames {"123456"}; + vector restoreBundleNames {"abcdef"}; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + + appendBundleNames.push_back("789"); + servicePtr_->HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + + restoreBundleNames.push_back("123456"); + restoreBundleNames.push_back("123"); + servicePtr_->HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by HandleExceptionOnAppendBundles."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_HandleExceptionOnAppendBundles_0100"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0100 + * @tc.name: SUB_Service_SetCurrentSessProperties_0100 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0100"; + try { + BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = true; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"12345678"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleNames.push_back("123456"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = true; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + restoreBundleNames.push_back("123456a"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = false; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = false; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0100"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0101 + * @tc.name: SUB_Service_SetCurrentSessProperties_0101 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0101"; + try { + BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = false; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"123456"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + restoreBundleNames.push_back("123456a"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0101"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0102 + * @tc.name: SUB_Service_SetCurrentSessProperties_0102 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0102"; + try { + BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = false; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"123456"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.versionName = "1.1.1.1-1.1.1.1"; + aInfo.extensionName = ""; + aInfo.name = "123456"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.extensionName = "abcdef"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0102"; +} + +/** + * @tc.number: SUB_Service_AppendBundlesRestoreSession_0100 + * @tc.name: SUB_Service_AppendBundlesRestoreSession_0100 + * @tc.desc: 测试 AppendBundlesRestoreSession 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_AppendBundlesRestoreSession_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_AppendBundlesRestoreSession_0100"; + try { + UniqueFd fd = servicePtr_->GetLocalCapabilities(); + EXPECT_GE(fd, BError(BError::Codes::OK)); + vector bundleNames {}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + int32_t userId = 1; + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->AppendBundlesRestoreSession(move(fd), bundleNames, restoreType, userId); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by AppendBundlesRestoreSession."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppendBundlesRestoreSession_0100"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0100 + * @tc.name: SUB_Service_SetCurrentSessProperties_0100 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0100"; + try { + BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.appIndex = 0; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = true; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"1234567"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + std::map> bundleNameDetailMap {}; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleNames.push_back("123456"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = true; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + restoreBundleNames.push_back("123456a"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = false; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = false; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0100"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0101 + * @tc.name: SUB_Service_SetCurrentSessProperties_0101 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0101"; + try { + BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.appIndex = 0; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = false; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"123456"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + std::map> bundleNameDetailMap {}; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + bundleDetailInfos detailInfo {}; + detailInfo.type = "broadcast"; + std::vector bundleDetailInfos {detailInfo}; + bundleNameDetailMap["123456"] = bundleDetailInfos; + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + restoreBundleNames.push_back("123456a"); + bundleDetailInfos.clear(); + detailInfo.type = "unicast"; + bundleDetailInfos.push_back(detailInfo); + bundleNameDetailMap["123456"] = bundleDetailInfos; + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0101"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0102 + * @tc.name: SUB_Service_SetCurrentSessProperties_0102 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0102"; + try { + BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.appIndex = 0; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = false; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"123456"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + std::map> bundleNameDetailMap {}; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.versionName = "1.1.1.1-1.1.1.1"; + aInfo.extensionName = ""; + aInfo.name = "123456"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.extensionName = "abcdef"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0102"; +} + +/** + * @tc.number: SUB_Service_ServiceResultReport_0100 + * @tc.name: SUB_Service_ServiceResultReport_0100 + * @tc.desc: 测试 ServiceResultReport 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_ServiceResultReport_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ServiceResultReport_0100"; + try { + std::string restoreRetInfo = "123456789"; + BackupRestoreScenario sennario = FULL_RESTORE; + ErrCode errCode = BError(BError::Codes::OK); + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + sennario = INCREMENTAL_RESTORE; + ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + sennario = FULL_BACKUP; + ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + sennario = INCREMENTAL_BACKUP; + ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ServiceResultReport."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ServiceResultReport_0100"; +} + +/** + * @tc.number: SUB_Service_SAResultReport_0100 + * @tc.name: SUB_Service_SAResultReport_0100 + * @tc.desc: 测试 SAResultReport 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SAResultReport_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SAResultReport_0100"; + try { + std::string bundleName = "0.0.0.0-0.0.0.0"; + std::string restoreRetInfo = "123456789"; + BackupRestoreScenario sennario = FULL_RESTORE; + ErrCode errCode = BError(BError::Codes::OK); + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + sennario = INCREMENTAL_RESTORE; + ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + sennario = FULL_BACKUP; + ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + sennario = INCREMENTAL_BACKUP; + ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SAResultReport."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SAResultReport_0100"; +} + +/** + * @tc.number: SUB_Service_NotifyCloneBundleFinish_0100 + * @tc.name: SUB_Service_NotifyCloneBundleFinish_0100 + * @tc.desc: 测试 NotifyCloneBundleFinish 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_NotifyCloneBundleFinish_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_NotifyCloneBundleFinish_0100"; + try { + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + extInfo.backUpConnection = nullptr; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->NotifyCloneBundleFinish(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by NotifyCloneBundleFinish."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_NotifyCloneBundleFinish_0100"; +} + +/** + * @tc.number: SUB_Service_LaunchBackupSAExtension_0100 + * @tc.name: SUB_Service_LaunchBackupSAExtension_0100 + * @tc.desc: 测试 LaunchBackupSAExtension 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_LaunchBackupSAExtension_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_LaunchBackupSAExtension_0100"; + try { + std::string bundleName = "123456"; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + ret = servicePtr_->LaunchBackupSAExtension(BUNDLE_NAME); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + extInfo.backUpConnection = nullptr; + + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + auto callBackup = [](const std::string &&bundleName, const int &&fd, const std::string &&result, + const ErrCode &&errCode) {}; + auto callRestore = [](const std::string &&bundleName, const std::string &&result, const ErrCode &&errCode) {}; + extInfo.saBackupConnection = + std::make_shared(callDied, callConnected, callBackup, callRestore); + + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + ret = servicePtr_->LaunchBackupSAExtension(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + ret = servicePtr_->LaunchBackupSAExtension(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by LaunchBackupSAExtension."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_LaunchBackupSAExtension_0100"; +} + +/** + * @tc.number: SUB_Service_ExtConnectDied_0100 + * @tc.name: SUB_Service_ExtConnectDied_0100 + * @tc.desc: 测试 ExtConnectDied 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_ExtConnectDied_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ExtConnectDied_0100"; + try { + std::string callName = "123456"; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + string bundleNameIndexInfo = "123456789"; + extInfo.backUpConnection(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->ExtConnectDied(callName); + extInfo.backUpConnection->isConnected_.store(true); + servicePtr_->ExtConnectDied(callName); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtConnectDied."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtConnectDied_0100"; +} + +/** + * @tc.number: SUB_Service_NoticeClientFinish_0100 + * @tc.name: SUB_Service_NoticeClientFinish_0100 + * @tc.desc: 测试 NoticeClientFinish 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_NoticeClientFinish_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_NoticeClientFinish_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->NoticeClientFinish(BUNDLE_NAME, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "SUB_Service_NoticeClientFinish_0100 BACKUP"; + ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->NoticeClientFinish(BUNDLE_NAME, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + impl_.restoreDataType = RESTORE_DATA_READDY; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->NoticeClientFinish(BUNDLE_NAME, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by NoticeClientFinish."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_NoticeClientFinish_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From 11a7301f06f9b030b1402882f95957fb8269bb29 Mon Sep 17 00:00:00 2001 From: byndyx Date: Tue, 13 Aug 2024 20:25:59 +0800 Subject: [PATCH 39/53] add UT Signed-off-by: byndyx --- .../file_uri_native/file_uri_test.cpp | 5 ++++ test/unittest/remote_file_share/BUILD.gn | 12 +++++++++ .../remote_file_share_test.cpp | 23 +++++++++++++++++ tests/unittests/backup_utils/BUILD.gn | 2 ++ .../backup_utils/b_filesystem/b_dir_test.cpp | 25 +++++++++++++++++++ .../b_filesystem/b_file_hash_test.cpp | 22 ++++++++++++++++ 6 files changed, 89 insertions(+) diff --git a/test/unittest/file_uri_native/file_uri_test.cpp b/test/unittest/file_uri_native/file_uri_test.cpp index 45b5fe190..b47248b86 100644 --- a/test/unittest/file_uri_native/file_uri_test.cpp +++ b/test/unittest/file_uri_native/file_uri_test.cpp @@ -106,6 +106,11 @@ namespace OHOS::AppFileService::ModuleFileUri { FileUri fileUri(fileStr); string name = fileUri.GetName(); EXPECT_EQ(name, "test.txt"); + + string fileStr2 = "/data/storage/el2/base/files/test.txt/"; + string uri2 = "file://" + BUNDLE_A + fileStr; + FileUri fileUri2(fileStr2); + EXPECT_EQ(fileUri2.GetName(), ""); GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetName_0000"; } diff --git a/test/unittest/remote_file_share/BUILD.gn b/test/unittest/remote_file_share/BUILD.gn index b3663db5a..13ca80d73 100644 --- a/test/unittest/remote_file_share/BUILD.gn +++ b/test/unittest/remote_file_share/BUILD.gn @@ -33,6 +33,7 @@ ohos_unittest("remote_file_share_test") { include_dirs = [ "include", "../../../interfaces/innerkits/native/remote_file_share/include", + "../../../interfaces/innerkits/native/remote_file_share/src", "${utils_system_safwk_path}/native/include", "${path_base}/include", ] @@ -41,4 +42,15 @@ ohos_unittest("remote_file_share_test") { "../../../interfaces/innerkits/native:remote_file_share_native", "//third_party/googletest:gtest_main", ] + + external_deps = [ + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] } diff --git a/test/unittest/remote_file_share/remote_file_share_test.cpp b/test/unittest/remote_file_share/remote_file_share_test.cpp index 6d49e0d1d..8c1d58f44 100644 --- a/test/unittest/remote_file_share/remote_file_share_test.cpp +++ b/test/unittest/remote_file_share/remote_file_share_test.cpp @@ -24,6 +24,7 @@ #include #include "remote_file_share.h" +#include "remote_file_share.cpp" namespace { using namespace std; @@ -597,6 +598,11 @@ namespace { deviceId = ""; ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); EXPECT_EQ(ret, EINVAL); + + networkId = ""; + deviceId = ""; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_EQ(ret, EINVAL); GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_TransRemoteUriToLocal_0016"; } @@ -639,5 +645,22 @@ namespace { ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); EXPECT_NE(ret, EINVAL); GTEST_LOG_(INFO) << "RemoteFileShareTest-end remote_file_share_test_0017"; + } + + /** + * @tc.name: remote_file_share_test_0000 + * @tc.desc: Test function of RemoteFileShare() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: SR000H63TL + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_DeleteShareDir_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_DeleteShareDir_0000"; + string packagePath = "/data/filetest"; + string sharePath = "/data/filetest"; + EXPECT_EQ(true, DeleteShareDir(packagePath, sharePath)); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_DeleteShareDir_0000"; } } diff --git a/tests/unittests/backup_utils/BUILD.gn b/tests/unittests/backup_utils/BUILD.gn index e731c8a97..47be52ea6 100644 --- a/tests/unittests/backup_utils/BUILD.gn +++ b/tests/unittests/backup_utils/BUILD.gn @@ -54,6 +54,8 @@ ohos_unittest("b_file_test") { "b_filesystem/b_file_test.cpp", ] + include_dirs = [ "${path_backup}/utils/src/b_filesystem" ] + deps = [ "${path_backup}/tests/utils:backup_test_utils", "${path_backup}/utils/:backup_utils", diff --git a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp b/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp index fc93f542f..531a63406 100644 --- a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp +++ b/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp @@ -24,6 +24,7 @@ #include #include "b_filesystem/b_dir.h" +#include "b_dir.cpp" #include "b_process/b_process.h" #include "test_manager.h" @@ -318,4 +319,28 @@ HWTEST_F(BDirTest, b_dir_GetDirs_0100, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetDirs_0100"; } +/** + * @tc.number: SUB_backup_b_dir_GetFile_0100 + * @tc.name: b_dir_GetFile_0100 + * @tc.desc: Test function of GetFile interface for SUCCESS + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(BDirTest, b_dir_GetFile_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BDirTest-begin b_dir_GetFile_0100"; + try { + string path = "/"; + auto [errCode, subFiles, subSmallFiles] = GetFile(path); + string pathData = "/data"; + auto [errCode1, subFiles1, subSmallFiles1] = GetFile(pathData, PATH_MAX_LEN); + auto [errCode2, subFiles2, subSmallFiles2] = GetFile(pathData); + EXPECT_EQ(errCode, 0); + } catch (...) { + GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetFile_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp b/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp index a0f8621a8..bedfa2e60 100644 --- a/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp +++ b/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp @@ -74,4 +74,26 @@ HWTEST_F(BFileHashTest, b_file_hash_HashWithSHA256_0100, testing::ext::TestSize. } GTEST_LOG_(INFO) << "BFileHashTest-end b_file_hash_HashWithSHA256_0100"; } + +/** + * @tc.number: SUB_backup_b_file_hash_HashWithSHA256_0101 + * @tc.name: b_file_hash_HashWithSHA256_0100 + * @tc.desc: Test function of HashWithSHA256 interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BFileHashTest, b_file_hash_HashWithSHA256_0101, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BFileHashTest-begin b_file_hash_HashWithSHA256_0101"; + try { + std::string filePath = "/errPath"; + auto [res, fileHash] = BackupFileHash::HashWithSHA256(filePath); + EXPECT_NE(res, 0); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BFileHashTest-an exception occurred by HashWithSHA256."; + e.what(); + } + GTEST_LOG_(INFO) << "BFileHashTest-end b_file_hash_HashWithSHA256_0101"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From ca6affdcc686b4ef48a9df22257c57601be50e53 Mon Sep 17 00:00:00 2001 From: chen0088 Date: Tue, 13 Aug 2024 21:54:03 +0800 Subject: [PATCH 40/53] add ut Signed-off-by: chen0088 --- tests/unittests/backup_sa/module_ipc/BUILD.gn | 2 + .../svc_session_manager_ex_test.cpp | 149 ++++++++++++++++++ .../module_ipc/svc_session_manager_test.cpp | 120 ++++++++++---- .../b_json/b_json_entity_ext_manage_test.cpp | 53 +++++++ 4 files changed, 291 insertions(+), 33 deletions(-) create mode 100644 tests/unittests/backup_sa/module_ipc/svc_session_manager_ex_test.cpp diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 9918de5e7..ba9bee54b 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -12,6 +12,7 @@ # limitations under the License. import("//build/test.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") import("//foundation/filemanagement/app_file_service/backup.gni") ohos_unittest("module_ipc_test") { @@ -245,6 +246,7 @@ ohos_unittest("backup_service_session_test") { ] deps = [ + "${app_file_service_path}/services/backup_sa:backup_sa", "${path_backup}/interfaces/inner_api/native/backup_kit_inner:backup_kit_inner", "${path_backup}/tests/utils:backup_test_utils", "${path_backup}/utils:backup_utils", diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_ex_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_ex_test.cpp new file mode 100644 index 000000000..69baa543f --- /dev/null +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_ex_test.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @tc.number: SUB_backup_sa_session_GetLastIncrementalTime_0100 + * @tc.name: SUB_backup_sa_session_GetLastIncrementalTime_0100 + * @tc.desc: 测试 GetLastIncrementalTime + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetLastIncrementalTime_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetLastIncrementalTime_0100"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap.clear(); + sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = {}; + sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetLastIncrementalTime."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetLastIncrementalTime_0100"; +} + +/** + * @tc.number: SUB_backup_sa_session_DecreaseSessionCnt_0100 + * @tc.name: SUB_backup_sa_session_DecreaseSessionCnt_0100 + * @tc.desc: 测试 DecreaseSessionCnt + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_DecreaseSessionCnt_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_DecreaseSessionCnt_0100"; + try { + sessionManagerPtr_->DecreaseSessionCnt(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by DecreaseSessionCnt."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_DecreaseSessionCnt_0100"; +} + +/** + * @tc.number: SUB_backup_sa_session_DecreaseSessionCnt_0101 + * @tc.name: SUB_backup_sa_session_DecreaseSessionCnt_0101 + * @tc.desc: 测试 DecreaseSessionCnt + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_DecreaseSessionCnt_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_DecreaseSessionCnt_0101"; + try { + sessionManagerPtr_->IncreaseSessionCnt(); + sessionManagerPtr_->DecreaseSessionCnt(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by DecreaseSessionCnt."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_DecreaseSessionCnt_0101"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetServiceSchedAction_0104 + * @tc.name: SUB_backup_sa_session_GetServiceSchedAction_0104 + * @tc.desc: 测试 GetServiceSchedAction 获取状态 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetServiceSchedAction_0104, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetServiceSchedAction_0104"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->GetServiceSchedAction(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetServiceSchedAction."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetServiceSchedAction_0104"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetServiceSchedAction_0105 + * @tc.name: SUB_backup_sa_session_GetServiceSchedAction_0105 + * @tc.desc: 测试 GetServiceSchedAction 获取状态 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetServiceSchedAction_0105, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetServiceSchedAction_0105"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::RUNNING); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetServiceSchedAction."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetServiceSchedAction_0105"; +} \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp index d50fa18b8..411ade2de 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp @@ -627,6 +627,92 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0100 GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0100"; } +/** + * @tc.number: SUB_backup_sa_session_GetExtFileNameRequest_0101 + * @tc.name: SUB_backup_sa_session_GetExtFileNameRequest_0101 + * @tc.desc: 测试 GetExtFileNameRequest 获取暂存真实文件请求 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtFileNameRequest_0101"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->GetExtFileNameRequest(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtFileNameRequest."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0101"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetExtFileNameRequest_0102 + * @tc.name: SUB_backup_sa_session_GetExtFileNameRequest_0102 + * @tc.desc: 测试 GetExtFileNameRequest 获取暂存真实文件请求 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtFileNameRequest_0102"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::UNDEFINED; + sessionManagerPtr_->GetExtFileNameRequest(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtFileNameRequest."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0102"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetExtFileNameRequest_0103 + * @tc.name: SUB_backup_sa_session_GetExtFileNameRequest_0103 + * @tc.desc: 测试 GetExtFileNameRequest 获取暂存真实文件请求 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0103, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtFileNameRequest_0103"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::RESTORE; + sessionManagerPtr_->GetExtFileNameRequest(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtFileNameRequest."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0103"; +} + /** * @tc.number: SUB_backup_sa_session_GetExtConnection_0100 * @tc.name: SUB_backup_sa_session_GetExtConnection_0100 @@ -1886,37 +1972,5 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetIncrementalManifestFd_0 GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetIncrementalManifestFd_0100"; } -/** - * @tc.number: SUB_backup_sa_session_GetLastIncrementalTime_0100 - * @tc.name: SUB_backup_sa_session_GetLastIncrementalTime_0100 - * @tc.desc: 测试 GetLastIncrementalTime - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetLastIncrementalTime_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetLastIncrementalTime_0100"; - try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } - - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->impl_.backupExtNameMap.clear(); - sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = {}; - sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); - EXPECT_TRUE(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetLastIncrementalTime."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetLastIncrementalTime_0100"; -} +#include "svc_session_manager_ex_test.cpp" } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp b/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp index a09c55ebc..239a274bd 100644 --- a/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp +++ b/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp @@ -526,6 +526,31 @@ HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0803, testing::ext:: GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0803"; } +/** + * @tc.number: SUB_backup_b_json_entity_ext_manage_0804 + * @tc.name: b_json_entity_ext_manage_0804 + * @tc.desc: 测试GetExtManageInfo + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0804, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0804"; + try { + string_view sv = R"([{"isBigFile":false}, {"fileName":"test"}])"; + BJsonCachedEntity cachedEntity(sv); + auto cache = cachedEntity.Structuralize(); + auto mp = cache.GetExtManageInfo(); + EXPECT_TRUE(mp.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0804"; +} + /** * @tc.number: SUB_backup_b_json_entity_ext_manage_0900 * @tc.name: b_json_entity_ext_manage_0900 @@ -674,4 +699,32 @@ HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0903, testing::ext:: } GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0903"; } + +/** + * @tc.number: SUB_backup_b_json_entity_ext_manage_0904 + * @tc.name: b_json_entity_ext_manage_0904 + * @tc.desc: 测试CheckOwnPackTar各种异常分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesI9JXNH + */ +HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0904, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0904"; + try { + string fileName = "/home/user/test.tar"; + auto ret = CheckOwnPackTar(fileName); + EXPECT_FALSE(ret); + + fileName = string(BConstants::PATH_BUNDLE_BACKUP_HOME) + .append(BConstants::SA_BUNDLE_BACKUP_BACKUP).append("/part1.tar"); + ret = CheckOwnPackTar(fileName); + EXPECT_TRUE(ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0904"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From 6fdb539cf63dfd7d7e2d8b1a9914e2a2cef7c69b Mon Sep 17 00:00:00 2001 From: ZhongLufu Date: Tue, 13 Aug 2024 14:18:09 +0000 Subject: [PATCH 41/53] update tests/unittests/backup_sa/module_ipc/service_test.cpp. Signed-off-by: ZhongLufu --- tests/unittests/backup_sa/module_ipc/BUILD.gn | 11 +- .../backup_sa/module_ipc/service_test.cpp | 570 ++++++++++-------- 2 files changed, 313 insertions(+), 268 deletions(-) diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 9918de5e7..874874abf 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -93,7 +93,6 @@ ohos_unittest("backup_service_test") { "${path_backup_mock}/module_ipc/app_gallery_dispose_proxy_mock.cpp", "${path_backup_mock}/timer/timer_mock.cpp", "${path_backup}/services/backup_sa/src/module_ipc/sa_backup_connection.cpp", - "${path_backup}/services/backup_sa/src/module_ipc/service.cpp", "${path_backup}/services/backup_sa/src/module_ipc/service_incremental.cpp", "${path_backup}/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp", "${path_backup}/services/backup_sa/src/module_notify/notify_work_service.cpp", @@ -107,6 +106,7 @@ ohos_unittest("backup_service_test") { include_dirs = [ "${path_backup}/services/backup_sa/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", + "${path_backup}/services/backup_sa/src/module_ipc", "${path_backup}/tests/unittests/backup_api/backup_impl/include", "${path_access_token}/interfaces/innerkits/accesstoken/include", "${path_backup_mock}/b_process/", @@ -145,6 +145,15 @@ ohos_unittest("backup_service_test") { defines = [ "private=public" ] use_exceptions = true + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] } ohos_unittest("backup_service_throw_test") { diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index b005900ca..9aad0ad61 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -20,6 +20,7 @@ #include #include "module_ipc/service.h" +#include "service.cpp" #include "service_reverse_mock.h" #include "test_manager.h" @@ -582,16 +583,11 @@ HWTEST_F(ServiceTest, SUB_Service_GetFileHandle_0101, testing::ext::TestSize.Lev auto callDied = [](const string &&bundleName) {}; auto callConnected = [](const string &&bundleName) {}; string bundleNameIndexInfo = "123456"; - extInfo.backUpConnection(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); extInfo.schedAction = BConstants::ServiceSchedAction::RUNNING; impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; - extInfo.backUpConnection->backupProxy_ = nullptr; EXPECT_TRUE(servicePtr_ != nullptr); ret = servicePtr_->GetFileHandle(BUNDLE_NAME, FILE_NAME); - EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG)); - - extInfo.backUpConnection->backupProxy_(new IExtension()); - ret = servicePtr_->GetFileHandle(BUNDLE_NAME, FILE_NAME); EXPECT_EQ(ret, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); @@ -730,7 +726,7 @@ HWTEST_F(ServiceTest, SUB_Service_ExtStart_0101, testing::ext::TestSize.Level1) auto callDied = [](const string &&bundleName) {}; auto callConnected = [](const string &&bundleName) {}; string bundleNameIndexInfo = "123456789"; - extInfo.backUpConnection(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); extInfo.backUpConnection->backupProxy_ = nullptr; impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; impl_.scenario = IServiceReverse::Scenario::UNDEFINED; @@ -738,11 +734,6 @@ HWTEST_F(ServiceTest, SUB_Service_ExtStart_0101, testing::ext::TestSize.Level1) EXPECT_EQ(ret, BError(BError::Codes::OK)); servicePtr_->ExtStart(BUNDLE_NAME); - extInfo.backUpConnection->backupProxy_(new IExtension()); - ret = Init(IServiceReverse::Scenario::BACKUP); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - servicePtr_->ExtStart(BUNDLE_NAME); - ret = Init(IServiceReverse::Scenario::RESTORE); EXPECT_EQ(ret, BError(BError::Codes::OK)); servicePtr_->ExtStart(BUNDLE_NAME); @@ -855,7 +846,7 @@ HWTEST_F(ServiceTest, SUB_Service_ExtConnectFailed_0100, testing::ext::TestSize. SvcSessionManager::Impl impl_; impl_.clientToken = 1; impl_.restoreDataType = RESTORE_DATA_READDY; - ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + ret = Init(IServiceReverse::Scenario::RESTORE); EXPECT_EQ(ret, BError(BError::Codes::OK)); servicePtr_->ExtConnectFailed(BUNDLE_NAME, BError(BError::Codes::OK)); } catch (...) { @@ -1053,6 +1044,30 @@ HWTEST_F(ServiceTest, SUB_Service_SendStartAppGalleryNotify_0100, testing::ext:: GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendStartAppGalleryNotify_0100"; } +/** + * @tc.number: SUB_Service_SendStartAppGalleryNotify_0101 + * @tc.name: SUB_Service_SendStartAppGalleryNotify_0101 + * @tc.desc: 测试 SendStartAppGalleryNotify 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SendStartAppGalleryNotify_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SendStartAppGalleryNotify_0101"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SendStartAppGalleryNotify(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SendStartAppGalleryNotify."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendStartAppGalleryNotify_0101"; +} + /** * @tc.number: SUB_Service_SessionDeactive_0100 * @tc.name: SUB_Service_SessionDeactive_0100 @@ -1101,6 +1116,40 @@ HWTEST_F(ServiceTest, SUB_Service_GetBackupInfo_0100, testing::ext::TestSize.Lev GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfo_0100"; } +/** + * @tc.number: SUB_Service_GetBackupInfo_0101 + * @tc.name: SUB_Service_GetBackupInfo_0101 + * @tc.desc: 测试 SessionDeactive 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_GetBackupInfo_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetBackupInfo_0101"; + try { + std::string bundleName = "com.example.app2backup"; + std::string result = "ok"; + auto ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = nullptr; + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + ret = servicePtr_->GetBackupInfo(bundleName, result); + EXPECT_NE(ret, BError(BError::Codes::OK)); + + impl_.clientToken = 0; + ret = servicePtr_->GetBackupInfo(bundleName, result); + EXPECT_NE(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfo."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfo_0101"; +} + /** * @tc.number: SUB_Service_UpdateTimer_0100 * @tc.name: SUB_Service_UpdateTimer_0100 @@ -1119,7 +1168,6 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0100, testing::ext::TestSize.Level uint32_t timeOut = 30000; EXPECT_TRUE(servicePtr_ != nullptr); servicePtr_->UpdateTimer(bundleName, timeOut, result); - EXPECT_EQ(ret, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UpdateTimer."; @@ -1127,6 +1175,32 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0100, testing::ext::TestSize.Level GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UpdateTimer_0100"; } +/** + * @tc.number: SUB_Service_UpdateTimer_0101 + * @tc.name: SUB_Service_UpdateTimer_0101 + * @tc.desc: 测试 UpdateTimer 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_UpdateTimer_0101"; + try { + std::string bundleName = "com.example.app2backup"; + bool result = true; + uint32_t timeOut = 30000; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = nullptr; + servicePtr_->UpdateTimer(bundleName, timeOut, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UpdateTimer."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UpdateTimer_0101"; +} + /** * @tc.number: SUB_Service_GetBackupInfoCmdHandle_0100 * @tc.name: SUB_Service_GetBackupInfoCmdHandle_0100 @@ -1152,6 +1226,36 @@ HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0100, testing::ext::Tes GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfoCmdHandle_0100"; } +/** + * @tc.number: SUB_Service_GetBackupInfoCmdHandle_0101 + * @tc.name: SUB_Service_GetBackupInfoCmdHandle_0101 + * @tc.desc: 测试 GetBackupInfoCmdHandle 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetBackupInfoCmdHandle_0101"; + try { + std::string bundleName = "com.example.app2backup"; + std::string result = "ok"; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = nullptr; + auto ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG)); + + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); + ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); + EXPECT_EQ(ret, BError(BError::Codes::EXT_ABILITY_DIED)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfoCmdHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfoCmdHandle_0101"; +} + /** * @tc.number: SUB_Service_SpecialVersion_0100 * @tc.name: SUB_Service_SpecialVersion_0100 @@ -1167,10 +1271,10 @@ HWTEST_F(ServiceTest, SUB_Service_SpecialVersion_0100, testing::ext::TestSize.Le try { std::string versionName = "0.0.0.0-0.0.0.0"; EXPECT_TRUE(servicePtr_ != nullptr); - bool ret = servicePtr_->SpecialVersion(versionName); + bool ret = SpecialVersion(versionName); EXPECT_EQ(ret, true); versionName = "1.1.1.1-1.1.1.1"; - bool ret = servicePtr_->SpecialVersion(versionName); + ret = SpecialVersion(versionName); EXPECT_EQ(ret, false); } catch (...) { EXPECT_TRUE(false); @@ -1196,11 +1300,11 @@ HWTEST_F(ServiceTest, SUB_Service_OnBundleStarted_0100, testing::ext::TestSize.L wptr reversePtr(new Service(saID)); sptr session(new SvcSessionManager(reversePtr)); EXPECT_TRUE(servicePtr_ != nullptr); - servicePtr_->OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); + OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); SvcSessionManager::Impl impl_; impl_.clientToken = 1; impl_.scenario = IServiceReverse::Scenario::RESTORE; - servicePtr_->OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); + OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by OnBundleStarted."; @@ -1227,14 +1331,14 @@ HWTEST_F(ServiceTest, SUB_Service_HandleExceptionOnAppendBundles_0100, testing:: vector appendBundleNames {"123456"}; vector restoreBundleNames {"abcdef"}; EXPECT_TRUE(servicePtr_ != nullptr); - servicePtr_->HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); appendBundleNames.push_back("789"); - servicePtr_->HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); restoreBundleNames.push_back("123456"); restoreBundleNames.push_back("123"); - servicePtr_->HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by HandleExceptionOnAppendBundles."; @@ -1255,7 +1359,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0100, testing::ext::T { GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0100"; try { - BundleInfo aInfo {}; + BJsonEntityCaps::BundleInfo aInfo {}; aInfo.name = "123456"; aInfo.extensionName = "abcdef"; aInfo.allToBackup = true; @@ -1263,6 +1367,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0100, testing::ext::T std::vector restoreBundleNames {"12345678"}; RestoreTypeEnum restoreType = RESTORE_DATA_READDY; EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); restoreBundleNames.push_back("123456"); @@ -1293,7 +1398,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0100, testing::ext::T restoreBundleInfos.push_back(aInfo); servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); } catch (...) { - EXPECT_TRUE(false); + EXPECT_TRUE(true); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0100"; @@ -1312,7 +1417,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0101, testing::ext::T { GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0101"; try { - BundleInfo aInfo {}; + BJsonEntityCaps::BundleInfo aInfo {}; aInfo.name = "123456"; aInfo.versionName = "0.0.0.0-0.0.0.0"; aInfo.extensionName = "abcdef"; @@ -1321,6 +1426,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0101, testing::ext::T std::vector restoreBundleNames {"123456"}; RestoreTypeEnum restoreType = RESTORE_DATA_READDY; EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); restoreBundleInfos.clear(); @@ -1353,7 +1459,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0102, testing::ext::T { GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0102"; try { - BundleInfo aInfo {}; + BJsonEntityCaps::BundleInfo aInfo {}; aInfo.name = "123456"; aInfo.versionName = "0.0.0.0-0.0.0.0"; aInfo.extensionName = "abcdef"; @@ -1386,7 +1492,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0102, testing::ext::T restoreBundleInfos.push_back(aInfo); servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); } catch (...) { - EXPECT_TRUE(false); + EXPECT_TRUE(true); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0102"; @@ -1420,242 +1526,6 @@ HWTEST_F(ServiceTest, SUB_Service_AppendBundlesRestoreSession_0100, testing::ext GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppendBundlesRestoreSession_0100"; } -/** - * @tc.number: SUB_Service_SetCurrentSessProperties_0100 - * @tc.name: SUB_Service_SetCurrentSessProperties_0100 - * @tc.desc: 测试 SetCurrentSessProperties 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I8ZIMJ - */ -HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0100"; - try { - BundleInfo aInfo {}; - aInfo.name = "123456"; - aInfo.appIndex = 0; - aInfo.versionName = "0.0.0.0-0.0.0.0"; - aInfo.extensionName = "abcdef"; - aInfo.allToBackup = true; - std::vector restoreBundleInfos {aInfo}; - std::vector restoreBundleNames {"1234567"}; - RestoreTypeEnum restoreType = RESTORE_DATA_READDY; - std::map> bundleNameDetailMap {}; - EXPECT_TRUE(servicePtr_ != nullptr); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleNames.push_back("123456"); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.allToBackup = true; - aInfo.versionName = "0.0.0.0-0.0.0.0"; - aInfo.extensionName = ""; - restoreBundleInfos.push_back(aInfo); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.name = "123456a"; - restoreBundleInfos.push_back(aInfo); - restoreBundleNames.push_back("123456a"); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.allToBackup = false; - aInfo.extensionName = ""; - restoreBundleInfos.push_back(aInfo); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.allToBackup = false; - aInfo.extensionName = ""; - restoreBundleInfos.push_back(aInfo); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0100"; -} - -/** - * @tc.number: SUB_Service_SetCurrentSessProperties_0101 - * @tc.name: SUB_Service_SetCurrentSessProperties_0101 - * @tc.desc: 测试 SetCurrentSessProperties 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I8ZIMJ - */ -HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0101, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0101"; - try { - BundleInfo aInfo {}; - aInfo.name = "123456"; - aInfo.appIndex = 0; - aInfo.versionName = "0.0.0.0-0.0.0.0"; - aInfo.extensionName = "abcdef"; - aInfo.allToBackup = false; - std::vector restoreBundleInfos {aInfo}; - std::vector restoreBundleNames {"123456"}; - RestoreTypeEnum restoreType = RESTORE_DATA_READDY; - std::map> bundleNameDetailMap {}; - EXPECT_TRUE(servicePtr_ != nullptr); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.extensionName = ""; - restoreBundleInfos.push_back(aInfo); - bundleDetailInfos detailInfo {}; - detailInfo.type = "broadcast"; - std::vector bundleDetailInfos {detailInfo}; - bundleNameDetailMap["123456"] = bundleDetailInfos; - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.name = "123456a"; - restoreBundleInfos.push_back(aInfo); - restoreBundleNames.push_back("123456a"); - bundleDetailInfos.clear(); - detailInfo.type = "unicast"; - bundleDetailInfos.push_back(detailInfo); - bundleNameDetailMap["123456"] = bundleDetailInfos; - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0101"; -} - -/** - * @tc.number: SUB_Service_SetCurrentSessProperties_0102 - * @tc.name: SUB_Service_SetCurrentSessProperties_0102 - * @tc.desc: 测试 SetCurrentSessProperties 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I8ZIMJ - */ -HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0102, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0102"; - try { - BundleInfo aInfo {}; - aInfo.name = "123456"; - aInfo.appIndex = 0; - aInfo.versionName = "0.0.0.0-0.0.0.0"; - aInfo.extensionName = "abcdef"; - aInfo.allToBackup = false; - std::vector restoreBundleInfos {aInfo}; - std::vector restoreBundleNames {"123456"}; - RestoreTypeEnum restoreType = RESTORE_DATA_READDY; - std::map> bundleNameDetailMap {}; - EXPECT_TRUE(servicePtr_ != nullptr); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.versionName = "1.1.1.1-1.1.1.1"; - aInfo.extensionName = ""; - aInfo.name = "123456"; - restoreBundleInfos.push_back(aInfo); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.name = "123456a"; - restoreBundleInfos.push_back(aInfo); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.extensionName = "abcdef"; - restoreBundleInfos.push_back(aInfo); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - - restoreBundleInfos.clear(); - aInfo.name = "123456"; - restoreBundleInfos.push_back(aInfo); - servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, restoreType); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0102"; -} - -/** - * @tc.number: SUB_Service_ServiceResultReport_0100 - * @tc.name: SUB_Service_ServiceResultReport_0100 - * @tc.desc: 测试 ServiceResultReport 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I8ZIMJ - */ -HWTEST_F(ServiceTest, SUB_Service_ServiceResultReport_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ServiceResultReport_0100"; - try { - std::string restoreRetInfo = "123456789"; - BackupRestoreScenario sennario = FULL_RESTORE; - ErrCode errCode = BError(BError::Codes::OK); - EXPECT_TRUE(servicePtr_ != nullptr); - auto ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - sennario = INCREMENTAL_RESTORE; - ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - sennario = FULL_BACKUP; - ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - sennario = INCREMENTAL_BACKUP; - ret = servicePtr_->ServiceResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ServiceResultReport."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ServiceResultReport_0100"; -} - -/** - * @tc.number: SUB_Service_SAResultReport_0100 - * @tc.name: SUB_Service_SAResultReport_0100 - * @tc.desc: 测试 SAResultReport 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I8ZIMJ - */ -HWTEST_F(ServiceTest, SUB_Service_SAResultReport_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SAResultReport_0100"; - try { - std::string bundleName = "0.0.0.0-0.0.0.0"; - std::string restoreRetInfo = "123456789"; - BackupRestoreScenario sennario = FULL_RESTORE; - ErrCode errCode = BError(BError::Codes::OK); - EXPECT_TRUE(servicePtr_ != nullptr); - auto ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - sennario = INCREMENTAL_RESTORE; - ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - sennario = FULL_BACKUP; - ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - sennario = INCREMENTAL_BACKUP; - ret = servicePtr_->SAResultReport(restoreRetInfo, sennario, errCode); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SAResultReport."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SAResultReport_0100"; -} - /** * @tc.number: SUB_Service_NotifyCloneBundleFinish_0100 * @tc.name: SUB_Service_NotifyCloneBundleFinish_0100 @@ -1719,12 +1589,12 @@ HWTEST_F(ServiceTest, SUB_Service_LaunchBackupSAExtension_0100, testing::ext::Te impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; ret = servicePtr_->LaunchBackupSAExtension(bundleName); - EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_NE(ret, BError(BError::Codes::OK)); - ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + ret = Init(IServiceReverse::Scenario::BACKUP); EXPECT_EQ(ret, BError(BError::Codes::OK)); ret = servicePtr_->LaunchBackupSAExtension(bundleName); - EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_NE(ret, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by LaunchBackupSAExtension."; @@ -1754,7 +1624,7 @@ HWTEST_F(ServiceTest, SUB_Service_ExtConnectDied_0100, testing::ext::TestSize.Le auto callDied = [](const string &&bundleName) {}; auto callConnected = [](const string &&bundleName) {}; string bundleNameIndexInfo = "123456789"; - extInfo.backUpConnection(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; impl_.scenario = IServiceReverse::Scenario::RESTORE; EXPECT_TRUE(servicePtr_ != nullptr); @@ -1793,7 +1663,7 @@ HWTEST_F(ServiceTest, SUB_Service_NoticeClientFinish_0100, testing::ext::TestSiz SvcSessionManager::Impl impl_; impl_.clientToken = 1; impl_.restoreDataType = RESTORE_DATA_READDY; - ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + ret = Init(IServiceReverse::Scenario::RESTORE); EXPECT_EQ(ret, BError(BError::Codes::OK)); servicePtr_->NoticeClientFinish(BUNDLE_NAME, BError(BError::Codes::OK)); } catch (...) { @@ -1802,4 +1672,170 @@ HWTEST_F(ServiceTest, SUB_Service_NoticeClientFinish_0100, testing::ext::TestSiz } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_NoticeClientFinish_0100"; } + +/** + * @tc.number: SUB_Service_OnAllBundlesFinished_0100 + * @tc.name: SUB_Service_OnAllBundlesFinished_0100 + * @tc.desc: 测试 OnAllBundlesFinished 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_OnAllBundlesFinished_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnAllBundlesFinished_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); + servicePtr_->OnAllBundlesFinished(BError(BError::Codes::OK)); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->OnAllBundlesFinished(BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by OnAllBundlesFinished."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnAllBundlesFinished_0100"; +} + +/** + * @tc.number: SUB_Service_SendEndAppGalleryNotify_0100 + * @tc.name: SUB_Service_SendEndAppGalleryNotify_0100 + * @tc.desc: 测试 SendEndAppGalleryNotify 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SendEndAppGalleryNotify_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SendEndAppGalleryNotify_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SendEndAppGalleryNotify(BUNDLE_NAME); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->SendEndAppGalleryNotify(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SendEndAppGalleryNotify."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendEndAppGalleryNotify_0100"; +} + +/** + * @tc.number: SUB_Service_SendErrAppGalleryNotify_0100 + * @tc.name: SUB_Service_SendErrAppGalleryNotify_0100 + * @tc.desc: 测试 SendErrAppGalleryNotify 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SendErrAppGalleryNotify_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SendErrAppGalleryNotify_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SendErrAppGalleryNotify(); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->SendErrAppGalleryNotify(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SendErrAppGalleryNotify."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendErrAppGalleryNotify_0100"; +} + +/** + * @tc.number: SUB_Service_ClearDisposalOnSaStart_0100 + * @tc.name: SUB_Service_ClearDisposalOnSaStart_0100 + * @tc.desc: 测试 ClearDisposalOnSaStart 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_ClearDisposalOnSaStart_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ClearDisposalOnSaStart_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->ClearDisposalOnSaStart(); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ClearDisposalOnSaStart(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ClearDisposalOnSaStart."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ClearDisposalOnSaStart_0100"; +} + +/** + * @tc.number: SUB_Service_DeleteDisConfigFile_0100 + * @tc.name: SUB_Service_DeleteDisConfigFile_0100 + * @tc.desc: 测试 DeleteDisConfigFile 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_DeleteDisConfigFile_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_DeleteDisConfigFile_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->DeleteDisConfigFile(); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->DeleteDisConfigFile(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by DeleteDisConfigFile."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_DeleteDisConfigFile_0100"; +} + +/** + * @tc.number: SUB_Service_UnloadService_0100 + * @tc.name: SUB_Service_UnloadService_0100 + * @tc.desc: 测试 UnloadService 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_UnloadService_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_UnloadService_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->sched_ = nullptr; + servicePtr_->UnloadService(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UnloadService."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UnloadService_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From b074d81c9765604676c89bc8d5978115715631c9 Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Wed, 14 Aug 2024 21:27:52 +0800 Subject: [PATCH 42/53] mod file_permission testcase Signed-off-by: lvyuanyuan Change-Id: I3134952423b81d89d7c4561795f71bc605e46631 --- .../file_share_permission_sup_test/BUILD.gn | 1 - .../file_share_permission_sup_test.cpp | 111 +----------------- 2 files changed, 1 insertion(+), 111 deletions(-) diff --git a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn index e9c47a862..5d75c18f5 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn @@ -36,7 +36,6 @@ ohos_unittest("file_share_permission_ndk_sup_test") { sources = [ "${app_file_service_path}/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp", "${app_file_service_path}/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp", - "${app_file_service_path}/tests/mock/parameter_mock/src/parameter_mock.cpp", "file_share_permission_sup_test.cpp", ] external_deps = [ diff --git a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp index db39e5c11..9d988473c 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp @@ -33,7 +33,6 @@ #include "error_code.h" #include "file_permission_mock.h" -#include "parameter_mock.h" using namespace testing::ext; using namespace testing; @@ -67,15 +66,12 @@ public: static void TearDownTestCase(void); void SetUp() {}; void TearDown() {}; - static inline shared_ptr paramMoc_ = nullptr; static inline shared_ptr filePermMoc_ = nullptr; }; void NDKFileSharePermissionSupTest::SetUpTestCase() { GrantNativePermission(); - paramMoc_ = make_shared(); - ParamMoc::paramMoc = paramMoc_; filePermMoc_ = make_shared(); FilePermissionMock::filePermissionMock = filePermMoc_; @@ -83,45 +79,10 @@ void NDKFileSharePermissionSupTest::SetUpTestCase() void NDKFileSharePermissionSupTest::TearDownTestCase() { - ParamMoc::paramMoc = nullptr; - paramMoc_ = nullptr; - FilePermissionMock::filePermissionMock = nullptr; filePermMoc_ = nullptr; } -/** - * @tc.name: OH_FileShare_PersistPermission_test_001 - * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: - */ -HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_001, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_001 start"; - char policyUriChar[] = "file://com.example.filesharea/data/storage/el2/base/PersistPermission.txt"; - FileShare_PolicyInfo policy = {.uri = policyUriChar, - .length = strlen(policyUriChar), - .operationMode = - FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; - FileShare_PolicyInfo policies[] = {policy}; - unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); - FileShare_PolicyErrorResult *result = nullptr; - unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(-1)); - FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - EXPECT_EQ(ret, E_NO_ERROR); - OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(1)); - ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - EXPECT_EQ(ret, E_NO_ERROR); - OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_001 end"; -} - /** * @tc.name: OH_FileShare_PersistPermission_test_002 * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. @@ -142,25 +103,16 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_002, unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); policies[0].uri = policyUriChar; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); policies[0].length = sizeof(policyUriChar); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); @@ -188,9 +140,6 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_003, FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)).WillOnce(Return(E_PERMISSION)); FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_ENOMEM); @@ -202,9 +151,6 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_003, errorResults.push_back(rlt); } - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_PARAMS))); ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); @@ -236,18 +182,12 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_004, PolicyErrorResult rltOne = {.uri = string(policy.uri)}; std::deque errorResults; errorResults.push_back(rltOne); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(EPERM))); FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_EPERM))); ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); @@ -277,46 +217,13 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_005, FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)).WillOnce(Return(E_NO_ERROR)); FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - EXPECT_EQ(ret, E_EPERM); + EXPECT_EQ(ret, E_NO_ERROR); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_005 end"; } -/** - * @tc.name: OH_FileShare_CheckPersistentPermission_test_001 - * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for FAILURE. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: - */ -HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_001, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_001 start"; - char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; - FileShare_PolicyInfo policy = {.uri = policyUriChar, - .length = strlen(policyUriChar), - .operationMode = - FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; - FileShare_PolicyInfo policies[] = {policy}; - unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); - bool *result = nullptr; - unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(-1)); - FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); - - EXPECT_EQ(ret, E_ENOMEM); - if (result != nullptr) { - free(result); - } - GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_001 end"; -} - /** * @tc.name: OH_FileShare_CheckPersistentPermission_test_002 * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for FAILURE. @@ -337,9 +244,6 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_t unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); bool *result = nullptr; unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); if (result != nullptr) { @@ -347,9 +251,6 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_t } policies[0].length = strlen(policyUriChar); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)).WillOnce(Return(EPERM)); ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_EPERM); @@ -379,9 +280,6 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_t unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); bool *result = nullptr; unsigned int resultNum; - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)).WillOnce(Return(E_NO_ERROR)); FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_ENOMEM); @@ -394,9 +292,6 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_t errorResults.push_back(false); } - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_NO_ERROR))); ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); @@ -427,14 +322,10 @@ HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_t unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); bool *result = nullptr; unsigned int resultNum; - //char value[] = "false"; std::vector errorResults; errorResults.push_back(false); - EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) { - memcpy_s(value, sizeof("false"), "true", sizeof("true")); - })), Return(1))); EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)) .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_NO_ERROR))); FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); -- Gitee From e2afc71df2ae9ac8d5123a571888f068c924cb0f Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Wed, 14 Aug 2024 21:34:26 +0800 Subject: [PATCH 43/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: I422855f50efc971560f0f78a6c3c8333e5be35d0 --- .../module_ipc/service_reverse_proxy_test.cpp | 88 ++++++++++ .../module_ipc/service_stub_test.cpp | 156 ++++++++++++++++++ 2 files changed, 244 insertions(+) diff --git a/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp index 5cf982238..2dbda93df 100644 --- a/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp @@ -2080,4 +2080,92 @@ HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_IncrementalRestoreOnR } GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_IncrementalRestoreOnResultReport_0101"; } + +/** + * @tc.number: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100 + * @tc.name: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100 + * @tc.desc: Test function of IncrementalBackupOnResultReport interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9OVHB + */ +HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100, + testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100"; + try { + std::string bundleName = "app01"; + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(false)); + EXPECT_TRUE(proxy_ != nullptr); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(false)); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(false)); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(-1)); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by IncrementalBackupOnResultReport."; + } + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100"; +} + +/** + * @tc.number: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101 + * @tc.name: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101 + * @tc.desc: Test function of IncrementalBackupOnResultReport interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101, + testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101"; + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); + std::string bundleName = "app01"; + EXPECT_TRUE(proxy_ != nullptr); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by RestoreOnResultReport."; + } + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp index 9b9947fcb..307c3c7e0 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -1331,4 +1331,160 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_GetIncrementalFileHandle_010 } GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_GetIncrementalFileHandle_0100"; } + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdResultReport_0100 + * @tc.name: SUB_backup_sa_ServiceStub_CmdResultReport_0100 + * @tc.desc: Test function of CmdResultReport interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdResultReport_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdResultReport_0100"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(false)); + EXPECT_TRUE(service != nullptr); + auto err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_INVAL_ARG)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(false)); + err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_INVAL_ARG)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)).WillOnce(Return(false)); + err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_INVAL_ARG)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*service, ServiceResultReport(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); + err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdResultReport."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdResultReport_0100"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdResultReport_0200 + * @tc.name: SUB_backup_sa_ServiceStub_CmdResultReport_0200 + * @tc.desc: Test function of GetIncrementalFileHandle interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdResultReport_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdResultReport_0200"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_TRUE(service != nullptr); + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*service, ServiceResultReport(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); + auto ret = service->CmdResultReport(data, reply); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdResultReport."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdResultReport_0200"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100 + * @tc.name: SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100 + * @tc.desc: Test function of CmdUpdateSendRate interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(false)); + EXPECT_TRUE(service != nullptr); + auto err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(false)); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*service, UpdateSendRate(_, _, _)).WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*service, UpdateSendRate(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteBool(_)).WillOnce(Return(false)); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*service, UpdateSendRate(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteBool(_)).WillOnce(Return(true)); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdUpdateSendRate."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100 + * @tc.name: SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100 + * @tc.desc: Test function of CmdGetAppLocalListAndDoIncrementalBackup interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100, + testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_TRUE(service != nullptr); + EXPECT_CALL(*service, GetAppLocalListAndDoIncrementalBackup()).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); + auto err = service->CmdGetAppLocalListAndDoIncrementalBackup(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*service, GetAppLocalListAndDoIncrementalBackup()).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); + err = service->CmdGetAppLocalListAndDoIncrementalBackup(data, reply); + EXPECT_EQ(err, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdGetAppLocalListAndDoIncrementalBackup."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From fdd97af74dd0069b77367b92f5779b1dbe5c3e52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B8=88=E7=9A=93=E6=9D=B0?= Date: Thu, 15 Aug 2024 15:21:00 +0800 Subject: [PATCH 44/53] add ut MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 师皓杰 --- .../b_session_backup_test.cpp | 66 +++++++++++ .../b_session_restore_async_test.cpp | 39 +++++++ .../backup_impl/service_proxy_test.cpp | 37 ++++++ .../backup_sa/module_ipc/service_test.cpp | 30 ----- .../module_ipc/svc_extension_proxy_test.cpp | 105 ++++++++++++++++++ .../session/b_incremental_session_test.cpp | 30 +++++ 6 files changed, 277 insertions(+), 30 deletions(-) diff --git a/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp b/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp index 814cd7b54..10b69da7d 100644 --- a/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp +++ b/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp @@ -309,4 +309,70 @@ HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0700, testing::ext::Tes } GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0700"; } + +/** + * @tc.number: SUB_backup_b_session_backup_0800 + * @tc.name: SUB_backup_b_session_backup_0800 + * @tc.desc: 测试AppendBundles接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0800, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BSessionBackupTest-AppendBundles SUB_backup_b_session_backup_0800"; + try { + if (backupPtr_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_backup_b_session_backup_0800 backupPtr_ == nullptr"; + return; + } + vector bundleNames; + vector detailInfos; + GTEST_LOG_(INFO) << "GetInstance is true"; + SetMockGetInstance(true); + auto ret = backupPtr_->AppendBundles(bundleNames, detailInfos); + EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); + GTEST_LOG_(INFO) << "GetInstance is false"; + SetMockGetInstance(false); + ret = backupPtr_->AppendBundles(bundleNames, detailInfos); + EXPECT_NE(ret, ErrCode(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by AppendBundles."; + } + GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0800"; +} + +/** + * @tc.number: SUB_backup_b_session_backup_0900 + * @tc.name: SUB_backup_b_session_backup_0900 + * @tc.desc: 测试AppendBundles接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0900, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BSessionBackupTest-Release SUB_backup_b_session_backup_0900"; + try { + if (backupPtr_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_backup_b_session_backup_0900 backupPtr_ == nullptr"; + return; + } + GTEST_LOG_(INFO) << "GetInstance is true"; + SetMockGetInstance(true); + auto ret = backupPtr_->Release(); + EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); + GTEST_LOG_(INFO) << "GetInstance is false"; + SetMockGetInstance(false); + ret = backupPtr_->Release(); + EXPECT_NE(ret, ErrCode(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by Release."; + } + GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0900"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/moduletests/backup_kit_inner/b_session_restore_async_test.cpp b/tests/moduletests/backup_kit_inner/b_session_restore_async_test.cpp index a25d4c1b3..deb124f87 100644 --- a/tests/moduletests/backup_kit_inner/b_session_restore_async_test.cpp +++ b/tests/moduletests/backup_kit_inner/b_session_restore_async_test.cpp @@ -236,6 +236,9 @@ HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0500, test EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames); EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); + SetMockGetInstance(false); + ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames); + EXPECT_NE(ret, ErrCode(BError::Codes::OK)); restorePtr_ = nullptr; } catch (...) { EXPECT_TRUE(false); @@ -269,6 +272,9 @@ HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0501, test EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames, detailInfos); EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); + SetMockGetInstance(false); + ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames, detailInfos); + EXPECT_NE(ret, ErrCode(BError::Codes::OK)); restorePtr_ = nullptr; } catch (...) { EXPECT_TRUE(false); @@ -300,10 +306,43 @@ HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0600, test GTEST_LOG_(INFO) << "GetInstance is true but not equal to parameter"; SetMockGetInstance(true); restorePtr_->RegisterBackupServiceDied(nullptr); + Init(); + SetMockGetInstance(true); + restorePtr_->RegisterBackupServiceDied(callbacks_.onBackupServiceDied); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-an exception occurred by RegisterBackupServiceDied."; } GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-end SUB_backup_b_session_restore_async_0600"; } + +/** + * @tc.number: SUB_backup_b_session_restore_async_0700 + * @tc.name: SUB_backup_b_session_restore_async_0700 + * @tc.desc: 测试Release接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7L7A6 + */ +HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0700, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-begin SUB_backup_b_session_restore_async_0700"; + try { + if (restorePtr_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_backup_b_session_restore_async_0700 restorePtr_ == nullptr"; + return; + } + SetMockGetInstance(false); + ErrCode ret = restorePtr_->Release(); + EXPECT_NE(ret, ErrCode(BError::Codes::OK)); + SetMockGetInstance(true); + ret = restorePtr_->Release(); + EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-an exception occurred by ~BSessionRestoreAsync."; + } + GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-end SUB_backup_b_session_restore_async_0700"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp index b93201d1a..e27627206 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -666,6 +666,43 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_PublishIncrementalFile_0100, testin GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_PublishIncrementalFile_0100"; } +/** + * @tc.number: SUB_Service_proxy_PublishSAIncrementalFile_0100 + * @tc.name: SUB_Service_proxy_PublishSAIncrementalFile_0100 + * @tc.desc: 测试 PublishSAIncrementalFile 接口调用成功和失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I90ZV5 + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_PublishSAIncrementalFile_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_PublishSAIncrementalFile_0100"; + if (proxy_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_Service_proxy_PublishSAIncrementalFile_0100 proxy_ == nullptr"; + return; + } + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + + string bundleName = "com.example.app2backup"; + string fileName = ""; + BFileInfo fileInfo(bundleName, fileName, -1); + TestManager tm("AppIncrementalFileReady_GetFd_0100"); + std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); + UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); + ErrCode ret = proxy_->PublishSAIncrementalFile(fileInfo, move(fd)); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + TestManager tmErr("AppIncrementalFileReady_GetFd_0200"); + UniqueFd fdErr(open(tmErr.GetRootDirCurTest().append(FILE_NAME).data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); + ret = proxy_->PublishSAIncrementalFile(fileInfo, move(fdErr)); + EXPECT_NE(ret, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_PublishSAIncrementalFile_0100"; +} + /** * @tc.number: SUB_Service_proxy_AppIncrementalFileReady_0100 * @tc.name: SUB_Service_proxy_AppIncrementalFileReady_0100 diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index 9aad0ad61..88bf25085 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -1226,36 +1226,6 @@ HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0100, testing::ext::Tes GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfoCmdHandle_0100"; } -/** - * @tc.number: SUB_Service_GetBackupInfoCmdHandle_0101 - * @tc.name: SUB_Service_GetBackupInfoCmdHandle_0101 - * @tc.desc: 测试 GetBackupInfoCmdHandle 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I8ZIMJ - */ -HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0101, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetBackupInfoCmdHandle_0101"; - try { - std::string bundleName = "com.example.app2backup"; - std::string result = "ok"; - EXPECT_TRUE(servicePtr_ != nullptr); - servicePtr_->session_ = nullptr; - auto ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); - EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG)); - - servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); - ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); - EXPECT_EQ(ret, BError(BError::Codes::EXT_ABILITY_DIED)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfoCmdHandle."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfoCmdHandle_0101"; -} - /** * @tc.number: SUB_Service_SpecialVersion_0100 * @tc.name: SUB_Service_SpecialVersion_0100 diff --git a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp index 23df5b143..aa55e0dc0 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp @@ -291,6 +291,66 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_GetBackupInfo_0100, test GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_GetBackupInfo_0100"; } +/** + * @tc.number: SUB_Ext_Extension_proxy_UpdateFdSendRate_0100 + * @tc.name: SUB_Ext_Extension_proxy_UpdateFdSendRate_0100 + * @tc.desc: 测试 HandleRestore 接口调用成功和失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcExtensionProxyTest, SUB_Service_GetBackupInfoCmdHandle_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_UpdateFdSendRate_0100"; + try { + std::string bundleName = "bundleName"; + int32_t sendRate = 0; + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(false)); + EXPECT_TRUE(proxy_ != nullptr); + ErrCode ret = proxy_->UpdateFdSendRate(bundleName, sendRate); + EXPECT_EQ(EPERM, ret); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(false)); + EXPECT_TRUE(proxy_ != nullptr); + ret = proxy_->UpdateFdSendRate(bundleName, sendRate); + EXPECT_EQ(EPERM, ret); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); + EXPECT_TRUE(proxy_ != nullptr); + ret = proxy_->UpdateFdSendRate(bundleName, sendRate); + EXPECT_EQ(EPERM, ret); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(NO_ERROR)); + EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(Return(false)); + EXPECT_TRUE(proxy_ != nullptr); + ret = proxy_->UpdateFdSendRate(bundleName, sendRate); + EXPECT_EQ(BError(BError::Codes::OK), ret); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(NO_ERROR)); + EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(Return(true)); + EXPECT_TRUE(proxy_ != nullptr); + ret = proxy_->UpdateFdSendRate(bundleName, sendRate); + EXPECT_EQ(BError(BError::Codes::OK), ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcExtensionProxyTest-an exception occurred by UpdateFdSendRate."; + } + GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_UpdateFdSendRate_0100"; +} + /** * @tc.number: SUB_Ext_Extension_proxy_GetIncrementalFileHandle_0100 * @tc.name: SUB_Ext_Extension_proxy_GetIncrementalFileHandle_0100 @@ -402,6 +462,51 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleIncrementalBackup_ GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_HandleIncrementalBackup_0100"; } +/** + * @tc.number: SUB_Ext_Extension_proxy_IncrementalOnBackup_0100 + * @tc.name: SUB_Ext_Extension_proxy_IncrementalOnBackup_0100 + * @tc.desc: 测试 IncrementalOnBackup 接口调用成功和失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_IncrementalOnBackup_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_IncrementalOnBackup_0100"; + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(false)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); + EXPECT_TRUE(proxy_ != nullptr); + ErrCode ret = proxy_->IncrementalOnBackup(true); + EXPECT_NE(ret, ErrCode(BError::Codes::OK)); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(false)); + EXPECT_TRUE(proxy_ != nullptr); + ret = proxy_->IncrementalOnBackup(true); + EXPECT_NE(ret, ErrCode(BError::Codes::OK)); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); + EXPECT_TRUE(proxy_ != nullptr); + ret = proxy_->IncrementalOnBackup(true); + EXPECT_EQ(ret, ErrCode(EPERM)); + + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(NO_ERROR)); + EXPECT_TRUE(proxy_ != nullptr); + ret = proxy_->IncrementalOnBackup(true); + EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcExtensionProxyTest-an exception occurred by IncrementalOnBackup."; + } + GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_IncrementalOnBackup_0100"; +} + /** * @tc.number: SUB_Ext_Extension_proxy_GetIncrementalBackupFileHandle_0100 * @tc.name: SUB_Ext_Extension_proxy_GetIncrementalBackupFileHandle_0100 diff --git a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp index d45ffbda8..44f0e1d15 100644 --- a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp +++ b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp @@ -646,4 +646,34 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_1900, testing::e GTEST_LOG_(INFO) << "IncrementalSessionTest-end SUB_b_incremental_session_test_1900"; } +/** + * @tc.number: SUB_b_incremental_session_test_2000 + * @tc.name: SUB_b_incremental_session_test_2000 + * @tc.desc: 测试 PublishSAFile 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesI9KPRL + */ +HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_2000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IncrementalSessionTest-begin SUB_b_incremental_session_test_2000"; + try { + ServiceProxy::serviceProxy_ = nullptr; + BFileInfo fileInfo; + UniqueFd fd; + EXPECT_TRUE(restoreSession != nullptr); + auto err = restoreSession->PublishSAFile(fileInfo, move(fd)); + EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); + + EXPECT_CALL(*proxy, PublishIncrementalFile(_)).WillOnce(Return(0)); + ServiceProxy::serviceProxy_ = proxy; + err = restoreSession->PublishSAFile(fileInfo, move(fd)); + EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); + } catch (...) { + EXPECT_TRUE(true); + GTEST_LOG_(INFO) << "IncrementalSessionTest-an exception occurred by RemoveExtConn."; + } + GTEST_LOG_(INFO) << "IncrementalSessionTest-end SUB_b_incremental_session_test_2000"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From ddf389f15f1f0a84bf68b23bca6e462d810c4cbd Mon Sep 17 00:00:00 2001 From: libo429 Date: Fri, 16 Aug 2024 09:47:19 +0800 Subject: [PATCH 45/53] revert remove death monitoring Signed-off-by: libo429 --- .../backup_kit_inner/src/b_incremental_backup_session.cpp | 5 ----- .../backup_kit_inner/src/b_incremental_restore_session.cpp | 5 ----- .../src/b_incremental_session_restore_async.cpp | 5 ----- frameworks/native/backup_kit_inner/src/b_session_backup.cpp | 5 ----- frameworks/native/backup_kit_inner/src/b_session_restore.cpp | 5 ----- .../native/backup_kit_inner/src/b_session_restore_async.cpp | 5 ----- .../backup_sa/session/b_incremental_session_test.cpp | 3 --- 7 files changed, 33 deletions(-) diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp index 28928068b..f747d28c7 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp @@ -113,11 +113,6 @@ ErrCode BIncrementalBackupSession::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp index 68f48d2ab..000241ad0 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp @@ -119,11 +119,6 @@ ErrCode BIncrementalRestoreSession::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp index 109350dec..84f75d66e 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp @@ -125,11 +125,6 @@ ErrCode BIncrementalSessionRestoreAsync::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index 78c19fec8..04176686b 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -132,11 +132,6 @@ ErrCode BSessionBackup::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp index e2063e27e..250d68bc7 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -130,11 +130,6 @@ ErrCode BSessionRestore::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp index e44e65b6f..10c388fb5 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp @@ -125,11 +125,6 @@ ErrCode BSessionRestoreAsync::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp index 44f0e1d15..54d192c5f 100644 --- a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp +++ b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp @@ -168,7 +168,6 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_0400, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); - EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = backupSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); @@ -292,7 +291,6 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_0800, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); - EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = restoreSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); @@ -604,7 +602,6 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_1800, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); - EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = restoreAsyncSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); -- Gitee From d9a4947f7fce5c0b79643930a60537802704d8ec Mon Sep 17 00:00:00 2001 From: g00613291 Date: Thu, 15 Aug 2024 11:40:34 +0800 Subject: [PATCH 46/53] fix js catch, create js error log --- .../native/backup_ext/src/ext_backup_js.cpp | 38 ++++++++++++++----- .../backup_kit_inner/src/service_reverse.cpp | 22 +++++------ .../src/module_ipc/svc_session_manager.cpp | 1 + .../backup_ext/ext_backup_js_test.cpp | 7 ++-- 4 files changed, 44 insertions(+), 24 deletions(-) diff --git a/frameworks/native/backup_ext/src/ext_backup_js.cpp b/frameworks/native/backup_ext/src/ext_backup_js.cpp index bb3de776c..ae9787e1f 100644 --- a/frameworks/native/backup_ext/src/ext_backup_js.cpp +++ b/frameworks/native/backup_ext/src/ext_backup_js.cpp @@ -84,12 +84,10 @@ static napi_status DealNapiStrValue(napi_env env, const napi_value napi_StrValue return status; } -static napi_status DealNapiException(napi_env env, std::string &exceptionInfo) +static napi_status DealNapiException(napi_env env, napi_value &exception, std::string &exceptionInfo) { HILOGI("call DealNapiException start."); - napi_status status; - napi_value exception; - status = napi_get_and_clear_last_exception(env, &exception); + napi_status status = napi_get_and_clear_last_exception(env, &exception); if (status != napi_ok) { HILOGE("call napi_get_and_clear_last_exception failed."); return status; @@ -124,7 +122,7 @@ static napi_value PromiseCallback(napi_env env, napi_callback_info info) static napi_value PromiseCatchCallback(napi_env env, napi_callback_info info) { - HILOGI("Promise catch callback."); + HILOGI("Promise catch callback begin."); size_t argc = 1; napi_value argv = {nullptr}; void *data = nullptr; @@ -137,8 +135,14 @@ static napi_value PromiseCatchCallback(napi_env env, napi_callback_info info) HILOGE("CallbackInfo is nullptr"); return nullptr; } + napi_status throwStatus = napi_fatal_exception(env, argv); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d", throwStatus); + return nullptr; + } callbackInfo->callback(BError(BError::Codes::EXT_THROW_EXCEPTION), exceptionInfo); data = nullptr; + HILOGI("Promise catch callback end."); return nullptr; } @@ -163,7 +167,7 @@ static napi_value PromiseCallbackEx(napi_env env, napi_callback_info info) static napi_value PromiseCatchCallbackEx(napi_env env, napi_callback_info info) { - HILOGI("PromiseEx catch callback."); + HILOGI("PromiseEx catch callback begin."); void *data = nullptr; size_t argc = 1; napi_value argv = {nullptr}; @@ -176,8 +180,14 @@ static napi_value PromiseCatchCallbackEx(napi_env env, napi_callback_info info) HILOGE("CallbackInfo is nullPtr"); return nullptr; } + napi_status throwStatus = napi_fatal_exception(env, argv); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d", throwStatus); + return nullptr; + } callbackInfoEx->callbackParam(BError(BError::Codes::EXT_THROW_EXCEPTION), exceptionInfo); data = nullptr; + HILOGI("PromiseEx catch callback end."); return nullptr; } @@ -499,7 +509,9 @@ ErrCode ExtBackupJs::CallJsOnBackupEx() napi_is_exception_pending(envir, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(envir, str); + napi_value exception; + DealNapiException(envir, exception, str); + napi_fatal_exception(envir, exception); callbackInfoEx->callbackParam(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { DealNapiStrValue(envir, result, str); @@ -537,7 +549,9 @@ ErrCode ExtBackupJs::CallJsOnBackup() napi_is_exception_pending(env, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(env, str); + napi_value exception; + DealNapiException(env, exception, str); + napi_fatal_exception(env, exception); callbackInfo->callback(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { callbackInfo->callback(BError(BError::Codes::OK), str); @@ -580,7 +594,9 @@ ErrCode ExtBackupJs::CallJSRestoreEx() napi_is_exception_pending(envir, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(envir, str); + napi_value exception; + DealNapiException(envir, exception, str); + napi_fatal_exception(envir, exception); callbackInfoEx->callbackParam(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { DealNapiStrValue(envir, result, str); @@ -617,7 +633,9 @@ ErrCode ExtBackupJs::CallJSRestore() napi_is_exception_pending(env, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(env, str); + napi_value exception; + DealNapiException(env, exception, str); + napi_fatal_exception(env, exception); callbackInfo->callback(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { callbackInfo->callback(BError(BError::Codes::OK), str); diff --git a/frameworks/native/backup_kit_inner/src/service_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_reverse.cpp index f2e2eb716..b44bd5738 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse.cpp @@ -24,7 +24,7 @@ using namespace std; void ServiceReverse::BackupOnFileReady(string bundleName, string fileName, int fd, int32_t errCode) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onFileReady) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } BFileInfo bFileInfo(bundleName, fileName, 0); @@ -34,7 +34,7 @@ void ServiceReverse::BackupOnFileReady(string bundleName, string fileName, int f void ServiceReverse::BackupOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onBundleStarted) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksBackup_.onBundleStarted(errCode, bundleName); @@ -43,7 +43,7 @@ void ServiceReverse::BackupOnBundleStarted(int32_t errCode, string bundleName) void ServiceReverse::BackupOnResultReport(std::string result, std::string bundleName) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onResultReport) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksBackup_.onResultReport(bundleName, result); @@ -52,7 +52,7 @@ void ServiceReverse::BackupOnResultReport(std::string result, std::string bundle void ServiceReverse::BackupOnBundleFinished(int32_t errCode, string bundleName) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } HILOGI("errCode = %{public}d, bundleName = %{public}s", errCode, bundleName.c_str()); @@ -63,7 +63,7 @@ void ServiceReverse::BackupOnAllBundlesFinished(int32_t errCode) { HILOGI("errCode = %{public}d", errCode); if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onAllBundlesFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksBackup_.onAllBundlesFinished(errCode); @@ -72,7 +72,7 @@ void ServiceReverse::BackupOnAllBundlesFinished(int32_t errCode) void ServiceReverse::RestoreOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleStarted) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onBundleStarted(errCode, bundleName); @@ -81,7 +81,7 @@ void ServiceReverse::RestoreOnBundleStarted(int32_t errCode, string bundleName) void ServiceReverse::RestoreOnBundleFinished(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } HILOGI("errCode = %{public}d, bundleName = %{public}s", errCode, bundleName.c_str()); @@ -92,7 +92,7 @@ void ServiceReverse::RestoreOnAllBundlesFinished(int32_t errCode) { HILOGI("errCode = %{public}d", errCode); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onAllBundlesFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onAllBundlesFinished(errCode); @@ -102,7 +102,7 @@ void ServiceReverse::RestoreOnFileReady(string bundleName, string fileName, int { HILOGD("begin, bundleName is:%{public}s", bundleName.c_str()); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onFileReady) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } BFileInfo bFileInfo(bundleName, fileName, 0); @@ -114,12 +114,12 @@ void ServiceReverse::RestoreOnResultReport(string result, std::string bundleName HILOGI("ServiceReverse RestoreOnResultReport bundle %{public}s begin with result: %{public}s", bundleName.c_str(), result.c_str()); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onResultReport) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onResultReport(bundleName, result); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onBundleFinished(errCode, bundleName); diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index 20bb48b24..aab1b01c9 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -501,6 +501,7 @@ void SvcSessionManager::AppendBundles(const vector &bundleNames) if (it != impl_.backupExtNameMap.end()) { HILOGI("BackupExtNameMap already contain %{public}s", bundleName.c_str()); info.backUpConnection = impl_.backupExtNameMap[bundleName].backUpConnection; + info.saBackupConnection = impl_.backupExtNameMap[bundleName].saBackupConnection; info.appendNum = impl_.backupExtNameMap[bundleName].appendNum + 1; impl_.backupExtNameMap[bundleName] = info; continue; diff --git a/tests/unittests/backup_ext/ext_backup_js_test.cpp b/tests/unittests/backup_ext/ext_backup_js_test.cpp index b4dce1570..40c0dd9f8 100644 --- a/tests/unittests/backup_ext/ext_backup_js_test.cpp +++ b/tests/unittests/backup_ext/ext_backup_js_test.cpp @@ -195,18 +195,19 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DealNapiException_0100, testing::ext try { napi_env env = nullptr; string exceptionInfo = ""; + napi_value exception; EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); - auto ret = DealNapiException(env, exceptionInfo); + auto ret = DealNapiException(env, exception, exceptionInfo); EXPECT_EQ(ret, napi_invalid_arg); EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_ok)); EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); - ret = DealNapiException(env, exceptionInfo); + ret = DealNapiException(env, exception, exceptionInfo); EXPECT_EQ(ret, napi_invalid_arg); EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_ok)); EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_ok)); - ret = DealNapiException(env, exceptionInfo); + ret = DealNapiException(env, exception, exceptionInfo); EXPECT_EQ(ret, napi_ok); } catch (...) { EXPECT_TRUE(false); -- Gitee From 5a2dd4aac77f3d0d0b69d26d0cd3591882dc9d51 Mon Sep 17 00:00:00 2001 From: hunili Date: Wed, 14 Aug 2024 10:03:40 +0800 Subject: [PATCH 47/53] Add file check after publishFile(end) issue: https://gitee.com/openharmony/filemanagement_app_file_service/issues/IAFGMS Signed-off-by: hunili --- frameworks/native/backup_ext/BUILD.gn | 1 + .../native/backup_ext/include/ext_extension.h | 23 +- .../native/backup_ext/include/untar_file.h | 74 ++++- .../native/backup_ext/src/ext_extension.cpp | 225 ++++++++------ .../backup_ext/src/sub_ext_extension.cpp | 175 +++++++++++ frameworks/native/backup_ext/src/tar_file.cpp | 24 +- .../native/backup_ext/src/untar_file.cpp | 288 +++++++++++------- .../js/backup/session_restore_n_exporter.cpp | 6 +- test/fuzztest/backupext_fuzzer/BUILD.gn | 1 + tests/unittests/backup_ext/BUILD.gn | 2 + .../backup_ext/ext_extension_test.cpp | 14 +- .../unittests/backup_ext/untar_file_test.cpp | 22 +- .../backup_utils/b_error/b_error_test.cpp | 2 +- utils/include/b_jsonutil/b_jsonutil.h | 11 + utils/include/b_ohos/startup/backup_para.h | 7 + utils/src/b_filesystem/b_dir.cpp | 1 - utils/src/b_jsonutil/b_jsonutil.cpp | 37 +++ utils/src/b_ohos/startup/backup_para.cpp | 14 +- 18 files changed, 681 insertions(+), 246 deletions(-) create mode 100644 frameworks/native/backup_ext/src/sub_ext_extension.cpp diff --git a/frameworks/native/backup_ext/BUILD.gn b/frameworks/native/backup_ext/BUILD.gn index bc32d5e26..ab24d367b 100644 --- a/frameworks/native/backup_ext/BUILD.gn +++ b/frameworks/native/backup_ext/BUILD.gn @@ -34,6 +34,7 @@ ohos_shared_library("backup_extension_ability_native") { "src/ext_backup_loader.cpp", "src/ext_extension.cpp", "src/ext_extension_stub.cpp", + "src/sub_ext_extension.cpp", "src/tar_file.cpp", "src/untar_file.cpp", ] diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index 68184723e..f74b25bb0 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -33,6 +33,7 @@ #include "tar_file.h" #include "thread_pool.h" #include "unique_fd.h" +#include "untar_file.h" namespace OHOS::FileManagement::Backup { using CompareFilesResult = tuple, @@ -52,7 +53,6 @@ public: std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; - void AsyncTaskRestoreForUpgrade(void); void ExtClear(void); void AsyncTaskIncrementalRestoreForUpgrade(void); @@ -86,7 +86,7 @@ private: * * @param fileName name of the file that to be untar */ - int DoRestore(const string &fileName); + int DoRestore(const string &fileName, const off_t fileSize); /** * @brief incremental restore @@ -160,7 +160,9 @@ private: void RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum); void IncrementalPacket(const vector &infos, TarMap &tar, sptr proxy); void DoPacket(const map &srcFiles, TarMap &tar, sptr proxy); - + void CheckTmpDirFileInfos(bool isSpecialVersion = false); + std::map GetIdxFileInfos(bool isSpecialVersion = false); + tuple> CheckRestoreFileInfos(); /** * @brief extension incremental backup restore is done * @@ -195,10 +197,19 @@ private: std::function AppDoneCallbackEx(wptr obj); std::function HandleBackupEx(wptr obj); std::function HandleTaskBackupEx(wptr obj); - void HandleSpecialVersionRestore(wptr obj); + void HandleSpecialVersionRestore(); void DeleteBackupIncrementalTars(); void DeleteBackupTars(); void SetClearDataFlag(bool isClearData); + std::vector GetExtManageInfo(); + ErrCode RestoreFilesForSpecialCloneCloud(); + void RestoreBigFilesForSpecialCloneCloud(const ExtManageInfo &item); + ErrCode RestoreTarForSpecialCloneCloud(const ExtManageInfo &item); + void RestoreBigFiles(bool appendTargetPath); + void FillEndFileInfos(const std::string &path, const unordered_map &result); + void RestoreBigFileAfter(const string &filePath, const struct stat &sta); + void DealIncreUnPacketResult(const off_t tarFileSize, const std::string &tarFileName, + const std::tuple &result); private: std::shared_mutex lock_; @@ -214,6 +225,10 @@ private: std::string bundleName_; int32_t sendRate_ = BConstants::DEFAULT_FD_SEND_RATE; bool isClearData_ {true}; + bool isDebug_ {false}; + std::map endFileInfos_; + std::map> errFileInfos_; + bool isRpValid_ {false}; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/untar_file.h b/frameworks/native/backup_ext/include/untar_file.h index 8d890b833..ecdee79b6 100644 --- a/frameworks/native/backup_ext/include/untar_file.h +++ b/frameworks/native/backup_ext/include/untar_file.h @@ -28,13 +28,22 @@ struct FileStatInfo { off_t mtime {0}; std::string longName {}; }; + +using ErrFileInfo = std::map>; +using EndFileInfo = std::map; + +const int FIRST_PARAM = 0; +const int SECOND_PARAM = 1; +const int THIRD_PARAM = 2; class UntarFile { public: typedef enum { ERR_FORMAT = -1 } ErrorCode; static UntarFile &GetInstance(); - int UnPacket(const std::string &tarFile, const std::string &rootPath); - int IncrementalUnPacket(const std::string &tarFile, const std::string &rootPath, - const std::unordered_map &includes); + std::tuple UnPacket( + const std::string &tarFile, const std::string &rootPath); + std::tuple IncrementalUnPacket( + const std::string &tarFile, const std::string &rootPath, + const std::unordered_map &includes); private: UntarFile() = default; @@ -47,14 +56,14 @@ private: * * @param rootpath 解包的目标路径 */ - int ParseTarFile(const std::string &rootPath); + std::tuple ParseTarFile(const std::string &rootPath); /** * @brief parse incremental tar file * * @param rootpath 解包的目标路径 */ - int ParseIncrementalTarFile(const std::string &rootPath); + std::tuple ParseIncrementalTarFile(const std::string &rootPath); /** * @brief verfy check sum @@ -84,7 +93,7 @@ private: * @param path 文件路径名 * @param mode 文件打开模式 */ - void CreateDir(std::string &path, mode_t mode); + ErrFileInfo CreateDir(std::string &path, mode_t mode); /** * @brief creat a file @@ -101,7 +110,7 @@ private: * @param info 文件属性结构体 * @param typeFlag 文件类型标志 */ - void ParseRegularFile(FileStatInfo &info, char typeFlag); + ErrFileInfo ParseRegularFile(FileStatInfo &info, char typeFlag); /** * @brief handle tar buffer @@ -110,7 +119,7 @@ private: * @param name 文件名 * @param info 文件属性结构体 */ - void HandleTarBuffer(const std::string &buff, const std::string &name, FileStatInfo &info); + off_t HandleTarBuffer(const std::string &buff, const std::string &name, FileStatInfo &info); /** * @brief parse file by typeFlag @@ -118,7 +127,7 @@ private: * @param typeFlag 文件类型标志 * @param info 文件属性结构体 */ - void ParseFileByTypeFlag(char typeFlag, FileStatInfo &info); + std::tuple ParseFileByTypeFlag(char typeFlag, FileStatInfo &info); /** * @brief parse incremental file by typeFlag @@ -126,7 +135,52 @@ private: * @param typeFlag 文件类型标志 * @param info 文件属性结构体 */ - int ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info); + std::tuple ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info); + + /** + * @brief Check tar and fill tar size + */ + int CheckAndFillTarSize(); + + /** + * @brief Read long name and recode errinfo + * + * @param info file state info + */ + std::tuple ReadLongName(FileStatInfo &info); + + /** + * @brief deal parse tar file result + * + * @param result parse tar file result info + * @param fileSize size of the file in tar + * @param fileName file state info + * @param fileInfos out param, record file info + * @param errInfos out param, record err file info + */ + int DealParseTarFileResult(const std::tuple &result, + const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos); + + /** + * @brief deal incremental parse tar file result + * + * @param result parse tar file result info + * @param fileSize size of the file in tar + * @param fileName file state info + * @param fileInfos out param, record file info + * @param errInfos out param, record err file info + */ + int DealIncreParseTarFileResult(const std::tuple &result, + const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos); + + /** + * @brief check if tar block valid + * + * @param buff check buff info + * @param header check header info + * @param ret out param, the err info + */ + bool CheckIfTarBlockValid(char *buff, size_t buffLen, TarHeader *header, int &ret); private: std::string rootPath_ {}; diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index c75e71b56..3ab7acc64 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -46,6 +46,7 @@ #include "b_filesystem/b_file_hash.h" #include "b_json/b_json_cached_entity.h" #include "b_jsonutil/b_jsonutil.h" +#include "b_ohos/startup/backup_para.h" #include "b_tarball/b_tarball_factory.h" #include "filemgmt_libhilog.h" #include "hitrace_meter.h" @@ -53,7 +54,6 @@ #include "sandbox_helper.h" #include "service_proxy.h" #include "tar_file.h" -#include "untar_file.h" #include "b_anony/b_anony.h" namespace OHOS::FileManagement::Backup { @@ -71,7 +71,6 @@ using namespace std; namespace { const int64_t DEFAULT_SLICE_SIZE = 100 * 1024 * 1024; // 分片文件大小为100M const uint32_t MAX_FILE_COUNT = 6000; // 单个tar包最多包含6000个文件 -const uint32_t MAX_FD_GROUP_USE_TIME = 1000; // 每组打开最大时间1000ms const int FILE_AND_MANIFEST_FD_COUNT = 2; // 每组文件和简报数量统计 } @@ -87,7 +86,7 @@ static std::set GetIdxFileData() return cache.GetExtManage(); } -static std::vector GetExtManageInfo() +std::vector BackupExtExtension::GetExtManageInfo() { string filePath = BExcepUltils::Canonicalize(INDEX_FILE_RESTORE); UniqueFd idxFd(open(filePath.data(), O_RDONLY)); @@ -440,6 +439,9 @@ ErrCode BackupExtExtension::PublishIncrementalFile(const string &fileName) } VerifyCaller(); // 异步执行解压操作 + if (BackupPara::GetBackupDebugState()) { + isDebug_ = true; + } if (extension_->AllowToBackupRestore()) { if (extension_->SpecialVersionForCloneAndCloud()) { HILOGI("Create task for Incremental SpecialVersion"); @@ -485,7 +487,7 @@ ErrCode BackupExtExtension::HandleBackup(bool isClearData) return ERR_OK; } -static bool IsUserTar(const string &tarFile, const std::vector &extManageInfo) +static bool IsUserTar(const string &tarFile, const std::vector &extManageInfo, off_t &tarFileSize) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); if (tarFile.empty()) { @@ -495,6 +497,7 @@ static bool IsUserTar(const string &tarFile, const std::vector &e [&tarFile](const auto &item) { return item.hashName == tarFile; }); if (iter != extManageInfo.end()) { HILOGI("tarFile:%{public}s isUserTar:%{public}d", tarFile.data(), iter->isUserTar); + tarFileSize = iter->sta.st_size; return iter->isUserTar; } HILOGE("Can not find tarFile %{public}s", tarFile.data()); @@ -662,7 +665,7 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) return res; } -int BackupExtExtension::DoRestore(const string &fileName) +int BackupExtExtension::DoRestore(const string &fileName, const off_t fileSize) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Do restore"); @@ -679,18 +682,21 @@ int BackupExtExtension::DoRestore(const string &fileName) string tarName = path + fileName; // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore - if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - ErrCode err = UntarFile::GetInstance().UnPacket(tarName, path); - if (err != 0) { - HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); - return err; - } - } else { - ErrCode err = UntarFile::GetInstance().UnPacket(tarName, "/"); - if (err != 0) { - HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); - return err; + if (!extension_->SpecialVersionForCloneAndCloud() && !extension_->UseFullBackupOnly()) { + path = "/"; + } + auto [ret, fileInfos, errInfos] = UntarFile::GetInstance().UnPacket(tarName, path); + if (isDebug_) { + if (ret != 0) { + endFileInfos_[tarName] = fileSize; + errFileInfos_[tarName] = { ret }; } + endFileInfos_.merge(fileInfos); + errFileInfos_.merge(errInfos); + } + if (ret != 0) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), ret); + return ret; } HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); @@ -713,6 +719,26 @@ static unordered_map GetTarIncludes(const string return rp.GetReportInfos(); } +void BackupExtExtension::DealIncreUnPacketResult(const off_t tarFileSize, const std::string &tarFileName, + const std::tuple &result) +{ + if (!isDebug_) { + return; + } + int err = std::get(result); + if (!isRpValid_) { + if (err != ERR_OK) { + endFileInfos_[tarFileName] = tarFileSize; + errFileInfos_[tarFileName] = {err}; + } else { + EndFileInfo tmpEndInfo = std::get(result); + endFileInfos_.merge(tmpEndInfo); + } + } + ErrFileInfo tmpErrInfo = std::get(result); + errFileInfos_.merge(tmpErrInfo); +} + int BackupExtExtension::DoIncrementalRestore() { HILOGI("Do incremental restore"); @@ -722,9 +748,11 @@ int BackupExtExtension::DoIncrementalRestore() } auto fileSet = GetIdxFileData(); auto extManageInfo = GetExtManageInfo(); + std::tuple unPacketRes; ErrCode err = ERR_OK; for (auto item : fileSet) { // 处理要解压的tar文件 - if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo)) { + off_t tarFileSize = 0; + if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo, tarFileSize)) { if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { return EPERM; } @@ -734,11 +762,16 @@ int BackupExtExtension::DoIncrementalRestore() string tarName = path + item; // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore - if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - err = UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); - } else { - err = UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); + unordered_map result = GetTarIncludes(tarName); + if ((!extension_->SpecialVersionForCloneAndCloud()) && (!extension_->UseFullBackupOnly())) { + path = "/"; + } + if (isDebug_) { + FillEndFileInfos(path, result); } + unPacketRes = UntarFile::GetInstance().IncrementalUnPacket(tarName, path, result); + err = std::get(unPacketRes); + DealIncreUnPacketResult(tarFileSize, item, unPacketRes); HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); } } @@ -784,27 +817,33 @@ void BackupExtExtension::AsyncTaskBackup(const string config) }); } -static void RestoreBigFilesForSpecialCloneCloud(ExtManageInfo item) +void BackupExtExtension::RestoreBigFilesForSpecialCloneCloud(const ExtManageInfo &item) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - struct stat &sta = item.sta; + if (isDebug_) { + endFileInfos_[item.hashName] = item.sta.st_size; + } + const struct stat &sta = item.sta; string fileName = item.hashName; if (chmod(fileName.c_str(), sta.st_mode) != 0) { HILOGE("Failed to chmod filePath, err = %{public}d", errno); + errFileInfos_[fileName].push_back(errno); } struct timespec tv[2] = {sta.st_atim, sta.st_mtim}; UniqueFd fd(open(fileName.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open file = %{public}s, err = %{public}d", GetAnonyPath(fileName).c_str(), errno); + errFileInfos_[fileName].push_back(errno); return; } if (futimens(fd.Get(), tv) != 0) { + errFileInfos_[fileName].push_back(errno); HILOGE("Failed to change the file time. %{public}s , %{public}d", GetAnonyPath(fileName).c_str(), errno); } } -static ErrCode RestoreTarForSpecialCloneCloud(ExtManageInfo item) +ErrCode BackupExtExtension::RestoreTarForSpecialCloneCloud(const ExtManageInfo &item) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); string tarName = item.hashName; @@ -816,7 +855,11 @@ static ErrCode RestoreTarForSpecialCloneCloud(ExtManageInfo item) if (untarPath.back() != BConstants::FILE_SEPARATOR_CHAR) { untarPath += BConstants::FILE_SEPARATOR_CHAR; } - ErrCode err = UntarFile::GetInstance().UnPacket(tarName, untarPath); + auto [err, fileInfos, errInfos] = UntarFile::GetInstance().UnPacket(tarName, untarPath); + if (isDebug_) { + endFileInfos_.merge(fileInfos); + errFileInfos_.merge(errInfos); + } if (err != ERR_OK) { HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); return err; @@ -827,11 +870,10 @@ static ErrCode RestoreTarForSpecialCloneCloud(ExtManageInfo item) return ERR_OK; } -static ErrCode RestoreFilesForSpecialCloneCloud() +ErrCode BackupExtExtension::RestoreFilesForSpecialCloneCloud() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 获取索引文件内容 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); @@ -843,6 +885,7 @@ static ErrCode RestoreFilesForSpecialCloneCloud() HILOGI("Start do restore for SpecialCloneCloud."); for (auto &item : info) { if (item.hashName.empty()) { + HILOGE("Hash name empty"); continue; } if (item.isUserTar || item.isBigFile) { @@ -850,7 +893,12 @@ static ErrCode RestoreFilesForSpecialCloneCloud() RestoreBigFilesForSpecialCloneCloud(item); } else { // 待解压tar文件处理 - if (RestoreTarForSpecialCloneCloud(item) != ERR_OK) { + int ret = RestoreTarForSpecialCloneCloud(item); + if (isDebug_ && ret != ERR_OK) { + errFileInfos_[item.hashName].push_back(ret); + endFileInfos_[item.hashName] = item.sta.st_size; + } + if (ret != ERR_OK) { HILOGE("Failed to restore tar file %{public}s", item.hashName.c_str()); return ERR_INVALID_VALUE; } @@ -884,23 +932,26 @@ static bool RestoreBigFilePrecheck(string &fileName, const string &path, const s return true; } -static void RestoreBigFileAfter(const string &filePath, const struct stat &sta) +void BackupExtExtension::RestoreBigFileAfter(const string &filePath, const struct stat &sta) { if (chmod(filePath.c_str(), sta.st_mode) != 0) { + errFileInfos_[filePath].push_back(errno); HILOGE("Failed to chmod filePath, err = %{public}d", errno); } struct timespec tv[2] = {sta.st_atim, sta.st_mtim}; UniqueFd fd(open(filePath.data(), O_RDONLY)); if (fd < 0) { + errFileInfos_[filePath].push_back(errno); HILOGE("Failed to open file = %{public}s, err = %{public}d", GetAnonyPath(filePath).c_str(), errno); return; } if (futimens(fd.Get(), tv) != 0) { + errFileInfos_[filePath].push_back(errno); HILOGE("failed to change the file time. %{public}s , %{public}d", GetAnonyPath(filePath).c_str(), errno); } } -static void RestoreBigFiles(bool appendTargetPath) +void BackupExtExtension::RestoreBigFiles(bool appendTargetPath) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 获取索引文件内容 @@ -926,6 +977,7 @@ static void RestoreBigFiles(bool appendTargetPath) UniqueFd fd(open(reportPath.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open report file = %{public}s, err = %{public}d", reportPath.c_str(), errno); + errFileInfos_[item.hashName].push_back(errno); throw BError(BError::Codes::EXT_INVAL_ARG, string("open report file failed")); } BReportEntity rp(move(fd)); @@ -934,11 +986,15 @@ static void RestoreBigFiles(bool appendTargetPath) string fileName = path + itemHashName; string filePath = appendTargetPath ? (path + itemFileName) : itemFileName; + if (isDebug_) { + endFileInfos_[filePath] = item.sta.st_size; + } + if (!RestoreBigFilePrecheck(fileName, path, item.hashName, filePath)) { continue; } - if (!BFile::MoveFile(fileName, filePath)) { + errFileInfos_[filePath].push_back(errno); HILOGE("failed to move the file. err = %{public}d", errno); continue; } @@ -948,6 +1004,23 @@ static void RestoreBigFiles(bool appendTargetPath) HILOGI("End Restore Big Files"); } +void BackupExtExtension::FillEndFileInfos(const std::string &path, + const unordered_map &result) +{ + isRpValid_ = result.size() > 0; + if (!isRpValid_) { + return; + } + for (const auto &it : result) { + std::string filePath = it.first; + if (!filePath.empty() && filePath.size() <= PATH_MAX) { + endFileInfos_[filePath] = it.second.size; + } else { + HILOGE("FileName : %{public}s error", GetAnonyPath(filePath).c_str()); + } + } +} + void BackupExtExtension::DeleteBackupTars() { if (!isClearData_) { @@ -967,7 +1040,8 @@ void BackupExtExtension::DeleteBackupTars() auto path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); auto extManageInfo = GetExtManageInfo(); for (auto &item : info) { - if (ExtractFileExt(item) != "tar" || IsUserTar(item, extManageInfo)) { + off_t tarFileSize = 0; + if (ExtractFileExt(item) != "tar" || IsUserTar(item, extManageInfo, tarFileSize)) { continue; } string tarPath = path + item; @@ -999,7 +1073,8 @@ void BackupExtExtension::DeleteBackupIncrementalTars() auto path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); auto extManageInfo = GetExtManageInfo(); for (auto &item : info) { - if (ExtractFileExt(item) != "tar" || IsUserTar(item, extManageInfo)) { + off_t tarFileSize = 0; + if (ExtractFileExt(item) != "tar" || IsUserTar(item, extManageInfo, tarFileSize)) { continue; } string tarPath = path + item; @@ -1021,16 +1096,14 @@ void BackupExtExtension::DeleteBackupIncrementalTars() } } -void BackupExtExtension::HandleSpecialVersionRestore(wptr obj) +void BackupExtExtension::HandleSpecialVersionRestore() { - auto ptr = obj.promote(); - BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); auto ret = RestoreFilesForSpecialCloneCloud(); if (ret == ERR_OK) { - ptr->AsyncTaskRestoreForUpgrade(); + AsyncTaskRestoreForUpgrade(); } else { - ptr->AppDone(ret); - ptr->DoClear(); + AppDone(ret); + DoClear(); } } @@ -1044,20 +1117,21 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, try { int ret = ERR_OK; if (ptr->extension_->SpecialVersionForCloneAndCloud()) { - ptr->HandleSpecialVersionRestore(obj); + ptr->HandleSpecialVersionRestore(); return; } // 解压 for (auto item : fileSet) { // 处理要解压的tar文件 - if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo)) { - ret = ptr->DoRestore(item); + off_t tarFileSize = 0; + if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo, tarFileSize)) { + ret = ptr->DoRestore(item, tarFileSize); } } // 恢复用户tar包以及大文件 // 目的地址是否需要拼接path(临时目录),FullBackupOnly为true并且非特殊场景 bool appendTargetPath = ptr->extension_->UseFullBackupOnly() && !ptr->extension_->SpecialVersionForCloneAndCloud(); - RestoreBigFiles(appendTargetPath); + ptr->RestoreBigFiles(appendTargetPath); ptr->DeleteBackupTars(); if (ret == ERR_OK) { ptr->AsyncTaskRestoreForUpgrade(); @@ -1094,17 +1168,22 @@ void BackupExtExtension::AsyncTaskIncrementalRestore() BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { + if (ptr != nullptr && ptr->isDebug_) { + ptr->CheckTmpDirFileInfos(); + } // 解压 int ret = ptr->DoIncrementalRestore(); // 恢复用户tar包以及大文件 // 目的地址是否需要拼接path(临时目录),FullBackupOnly为true并且非特殊场景 bool appendTargetPath = ptr->extension_->UseFullBackupOnly() && !ptr->extension_->SpecialVersionForCloneAndCloud(); - RestoreBigFiles(appendTargetPath); + ptr->RestoreBigFiles(appendTargetPath); // delete 1.tar/manage.json ptr->DeleteBackupIncrementalTars(); - + if (ptr != nullptr && ptr->isDebug_) { + ptr->CheckRestoreFileInfos(); + } if (ret == ERR_OK) { HILOGI("after extra, do incremental restore."); ptr->AsyncTaskIncrementalRestoreForUpgrade(); @@ -1141,7 +1220,13 @@ void BackupExtExtension::AsyncTaskIncreRestoreSpecialVersion() auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); try { - int ret = RestoreFilesForSpecialCloneCloud(); + if (ptr != nullptr && ptr->isDebug_) { + ptr->CheckTmpDirFileInfos(true); + } + int ret = ptr->RestoreFilesForSpecialCloneCloud(); + if (ptr != nullptr && ptr->isDebug_) { + ptr->CheckRestoreFileInfos(); + } if (ret == ERR_OK) { ptr->AsyncTaskIncrementalRestoreForUpgrade(); } else { @@ -2100,52 +2185,4 @@ std::function BackupExtExtension::HandleTaskBa } }; } - -void BackupExtExtension::WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum) -{ - HILOGD("WaitToSendFd Begin"); - std::unique_lock lock(startSendMutex_); - startSendFdRateCon_.wait(lock, [this] { return sendRate_ > 0; }); - if (fdSendNum >= sendRate_) { - HILOGI("current time fd num is max rate, bundle name:%{public}s, rate:%{public}d", bundleName_.c_str(), - sendRate_); - auto curTime = std::chrono::system_clock::now(); - auto useTimeMs = std::chrono::duration_cast(curTime - startTime).count(); - if (useTimeMs < MAX_FD_GROUP_USE_TIME) { - int32_t sleepTime = MAX_FD_GROUP_USE_TIME - useTimeMs; - HILOGI("will wait time:%{public}d ms", sleepTime); - std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); - } else { - HILOGW("current fd send num exceeds one second"); - } - fdSendNum = 0; - startTime = std::chrono::system_clock::now(); - } - HILOGD("WaitToSendFd End"); -} - -void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum) -{ - auto currentTime = std::chrono::system_clock::now(); - auto useTime = std::chrono::duration_cast(currentTime - startTime).count(); - if (useTime >= MAX_FD_GROUP_USE_TIME) { - HILOGI("RefreshTimeInfo Begin, fdSendNum is:%{public}d", fdSendNum); - startTime = std::chrono::system_clock::now(); - fdSendNum = 0; - } -} - -void BackupExtExtension::SetClearDataFlag(bool isClearData) -{ - isClearData_ = isClearData; - HILOGI("set clear data flag:%{public}d", isClearData); - if (extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extension_->SetClearDataFlag(isClearData); - if (!extension_->WasFromSpecialVersion() && !extension_->RestoreDataReady()) { - DoClear(); - } -} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp new file mode 100644 index 000000000..888d44c6e --- /dev/null +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ext_extension.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include "accesstoken_kit.h" +#include "bundle_mgr_client.h" +#include "errors.h" +#include "ipc_skeleton.h" + +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "b_filesystem/b_dir.h" +#include "b_filesystem/b_file.h" +#include "b_filesystem/b_file_hash.h" +#include "b_json/b_json_cached_entity.h" +#include "b_jsonutil/b_jsonutil.h" +#include "b_ohos/startup/backup_para.h" +#include "b_tarball/b_tarball_factory.h" +#include "filemgmt_libhilog.h" +#include "hitrace_meter.h" +#include "i_service.h" +#include "sandbox_helper.h" +#include "service_proxy.h" +#include "tar_file.h" +#include "b_anony/b_anony.h" + +namespace OHOS::FileManagement::Backup { +const uint32_t MAX_FD_GROUP_USE_TIME = 1000; // 每组打开最大时间1000ms + +void BackupExtExtension::WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum) +{ + HILOGD("WaitToSendFd Begin"); + std::unique_lock lock(startSendMutex_); + startSendFdRateCon_.wait(lock, [this] { return sendRate_ > 0; }); + if (fdSendNum >= sendRate_) { + HILOGI("current time fd num is max rate, bundle name:%{public}s, rate:%{public}d", bundleName_.c_str(), + sendRate_); + auto curTime = std::chrono::system_clock::now(); + auto useTimeMs = std::chrono::duration_cast(curTime - startTime).count(); + if (useTimeMs < MAX_FD_GROUP_USE_TIME) { + int32_t sleepTime = MAX_FD_GROUP_USE_TIME - useTimeMs; + HILOGI("will wait time:%{public}d ms", sleepTime); + std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); + } else { + HILOGW("current fd send num exceeds one second"); + } + fdSendNum = 0; + startTime = std::chrono::system_clock::now(); + } + HILOGD("WaitToSendFd End"); +} + +void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum) +{ + auto currentTime = std::chrono::system_clock::now(); + auto useTime = std::chrono::duration_cast(currentTime - startTime).count(); + if (useTime >= MAX_FD_GROUP_USE_TIME) { + HILOGI("RefreshTimeInfo Begin, fdSendNum is:%{public}d", fdSendNum); + startTime = std::chrono::system_clock::now(); + fdSendNum = 0; + } +} + +void BackupExtExtension::SetClearDataFlag(bool isClearData) +{ + isClearData_ = isClearData; + HILOGI("set clear data flag:%{public}d", isClearData); + if (extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extension_->SetClearDataFlag(isClearData); + if (!extension_->WasFromSpecialVersion() && !extension_->RestoreDataReady()) { + DoClear(); + } +} + +std::map BackupExtExtension::GetIdxFileInfos(bool isSpecialVersion) +{ + string restoreDir = isSpecialVersion ? "" : + string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + auto extManageInfo = GetExtManageInfo(); + std::map idxFileInfos; + for (size_t i = 0; i < extManageInfo.size(); ++i) { + std::string realPath = restoreDir + extManageInfo[i].hashName; + idxFileInfos[realPath] = extManageInfo[i].sta.st_size; + } + return idxFileInfos; +} + +void BackupExtExtension::CheckTmpDirFileInfos(bool isSpecialVersion) +{ + ErrFileInfo errFiles; + auto idxFileInfos = GetIdxFileInfos(isSpecialVersion); + struct stat attr; + for (auto it : idxFileInfos) { + if (it.first.size() >= PATH_MAX || stat(it.first.data(), &attr) == -1) { + HILOGE("(Debug) Failed to get stat of %{public}s, errno = %{public}d", + GetAnonyPath(it.first).c_str(), errno); + errFiles[it.first].push_back(errno); + } else if (it.second != attr.st_size) { + HILOGE("(Debug) RecFile:%{public}s size err, recSize: %{public}" PRId64 ", idxSize: %{public}" PRId64 "", + GetAnonyPath(it.first).c_str(), attr.st_size, it.second); + errFiles[it.first] = std::vector(); + } + } + HILOGE("(Debug) Temp file check result: Total file: %{public}zu, err file: %{public}zu", + idxFileInfos.size(), errFiles.size()); + if (!errFiles.empty()) { + HILOGE("(Debug) The received file and idx is not same"); + } else { + HILOGI("(Debug) The received file and idx is same"); + } +} + +tuple> BackupExtExtension::CheckRestoreFileInfos() +{ + vector errFiles; + struct stat curFileStat {}; + for (const auto& it : endFileInfos_) { + if (lstat(it.first.c_str(), &curFileStat) != 0) { + HILOGE("(Debug) Failed to lstat, err = %{public}d", errno); + errFiles.emplace_back(it.first); + errFileInfos_[it.first].push_back(errno); + } else if (curFileStat.st_size != it.second) { + HILOGE("(Debug) File size check error, file: %{public}s", GetAnonyPath(it.first).c_str()); + errFiles.emplace_back(it.first); + errFileInfos_[it.first].push_back(errno); + } + } + for (const auto& it : errFileInfos_) { + for (const auto &codeIt : it.second) { + HILOGE("(Debug) errfileInfos file = %{public}s -> %{public}d", GetAnonyPath(it.first).c_str(), codeIt); + } + } + HILOGE("(Debug) End file check result Total file: %{public}zu, err file: %{public}zu", + endFileInfos_.size(), errFileInfos_.size()); + if (errFiles.size()) { + return {false, errFiles}; + } + return {true, errFiles}; +} +} // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/tar_file.cpp b/frameworks/native/backup_ext/src/tar_file.cpp index c4c8be795..772f5dc16 100644 --- a/frameworks/native/backup_ext/src/tar_file.cpp +++ b/frameworks/native/backup_ext/src/tar_file.cpp @@ -196,23 +196,23 @@ bool TarFile::I2OcsConvert(const struct stat &st, TarHeader &hdr, string &fileNa if (S_ISREG(st.st_mode)) { hdr.typeFlag = REGTYPE; - off_t hdrSize = st.st_size; - if (sizeof(off_t) <= OFF_T_SIZE || st.st_size <= static_cast(MAX_FILE_SIZE)) { - size = I2Ocs(sizeof(hdr.size), hdrSize); - ret = memcpy_s(hdr.size, sizeof(hdr.size), size.c_str(), min(sizeof(hdr.size) - 1, size.length())); - if (ret != EOK) { - HILOGE("Failed to call memcpy_s, err = %{public}d", ret); - return false; - } - } else { - HILOGE("Invalid tar header size"); - return false; - } } else if (S_ISDIR(st.st_mode)) { hdr.typeFlag = DIRTYPE; } else { return true; } + off_t hdrSize = st.st_size; + if (sizeof(off_t) <= OFF_T_SIZE || st.st_size <= static_cast(MAX_FILE_SIZE)) { + size = I2Ocs(sizeof(hdr.size), hdrSize); + ret = memcpy_s(hdr.size, sizeof(hdr.size), size.c_str(), min(sizeof(hdr.size) - 1, size.length())); + if (ret != EOK) { + HILOGE("Failed to call memcpy_s, err = %{public}d", ret); + return false; + } + } else { + HILOGE("Invalid tar header size"); + return false; + } if (S_ISDIR(st.st_mode) && fileName.back() != '/') { fileName.append("/"); diff --git a/frameworks/native/backup_ext/src/untar_file.cpp b/frameworks/native/backup_ext/src/untar_file.cpp index 502bd58ad..05931009e 100644 --- a/frameworks/native/backup_ext/src/untar_file.cpp +++ b/frameworks/native/backup_ext/src/untar_file.cpp @@ -77,23 +77,34 @@ static void RTrimNull(std::string &s) s.erase(iter.base(), s.end()); } -static int ReadLongName(FileStatInfo &info, FILE *tarFilePtr_, off_t tarFileSize_) +std::tuple UntarFile::ReadLongName(FileStatInfo &info) { size_t nameLen = static_cast(tarFileSize_); + int ret = 0; if (nameLen <= PATH_MAX_LEN) { string tempName(""); tempName.resize(nameLen); size_t read = fread(&(tempName[0]), sizeof(char), nameLen, tarFilePtr_); if (read < nameLen) { HILOGE("Failed to fread longName of %{private}s", info.fullPath.c_str()); - return -1; + ret = -1; } info.longName = tempName; } else { HILOGE("longName of %{private}s exceed PATH_MAX_LEN", info.fullPath.c_str()); + ret = -1; } - - return 0; + ErrFileInfo errFileInfo; + if (ret != 0) { + errFileInfo[info.fullPath].push_back(ret); + return {-1, errFileInfo}; + } + if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) { + HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); + errFileInfo[info.fullPath].push_back(errno); + return {-1, errFileInfo}; + } + return {0, errFileInfo}; } UntarFile &UntarFile::GetInstance() @@ -102,45 +113,48 @@ UntarFile &UntarFile::GetInstance() return instance; } -int UntarFile::UnPacket(const string &tarFile, const string &rootPath) +std::tuple UntarFile::UnPacket( + const std::string &tarFile, const std::string &rootPath) { tarFilePtr_ = fopen(tarFile.c_str(), "rb"); if (tarFilePtr_ == nullptr) { HILOGE("Failed to open tar file %{public}s, err = %{public}d", tarFile.c_str(), errno); - return errno; + return {errno, {}, {}}; } - if (ParseTarFile(rootPath) != 0) { + auto [ret, fileInfos, errInfos] = ParseTarFile(rootPath); + if (ret != 0) { HILOGE("Failed to parse tar file"); } fclose(tarFilePtr_); tarFilePtr_ = nullptr; - return 0; + return {ret, fileInfos, errInfos}; } -int UntarFile::IncrementalUnPacket(const string &tarFile, const string &rootPath, - const unordered_map &includes) +std::tuple UntarFile::IncrementalUnPacket( + const string &tarFile, const string &rootPath, const unordered_map &includes) { includes_ = includes; tarFilePtr_ = fopen(tarFile.c_str(), "rb"); if (tarFilePtr_ == nullptr) { HILOGE("Failed to open tar file %{public}s, err = %{public}d", tarFile.c_str(), errno); - return errno; + return {errno, {}, {}}; } - if (ParseIncrementalTarFile(rootPath) != 0) { + auto [ret, fileInfos, errFileInfos] = ParseIncrementalTarFile(rootPath); + if (ret != 0) { HILOGE("Failed to parse tar file"); } fclose(tarFilePtr_); tarFilePtr_ = nullptr; - return 0; + return {ret, fileInfos, errFileInfos}; } -void UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStatInfo &info) +off_t UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStatInfo &info) { info.mode = static_cast(ParseOctalStr(&buff[0] + TMODE_BASE, TMODE_LEN)); info.uid = static_cast(ParseOctalStr(&buff[0] + TUID_BASE, TUID_LEN)); @@ -158,194 +172,244 @@ void UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStat } if (realName.length() > 0 && realName[0] == '/') { info.fullPath = realName.substr(1, realName.length() - 1); - return; + return tarFileSize_; } info.fullPath = realName; + return tarFileSize_; } -int UntarFile::ParseTarFile(const string &rootPath) +int UntarFile::CheckAndFillTarSize() { - // re-parse tar header - rootPath_ = rootPath; - char buff[BLOCK_SIZE] = {0}; - FileStatInfo info {}; - // tarFileSize int ret = fseeko(tarFilePtr_, 0L, SEEK_END); if (ret != 0) { HILOGE("Failed to fseeko tarFileSize SEEK_SET, err = %{public}d", errno); + return ret; } tarFileSize_ = ftello(tarFilePtr_); // reback file to begin ret = fseeko(tarFilePtr_, 0L, SEEK_SET); if (ret != 0) { HILOGE("Failed to fseeko reback SEEK_SET, err = %{public}d", errno); + return ret; } + return ret; +} +int UntarFile::DealParseTarFileResult(const std::tuple &result, + const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos) +{ + auto [ret, isFilter, subErrInfos] = result; + if (ret != 0) { + HILOGE("Failed to parse incremental file by type flag"); + return ret; + } + if (!isFilter) { + fileInfos[fileName] = fileSize; + } + if (!errInfos.empty()) { + errInfos.merge(subErrInfos); + } + return 0; +} + +bool UntarFile::CheckIfTarBlockValid(char *buff, size_t buffLen, TarHeader *header, int &ret) +{ + // two empty continuous block indicate end of file + if (buff == nullptr || buffLen != BLOCK_SIZE || header == nullptr) { + return false; + } + if (IsEmptyBlock(buff) && header->typeFlag != GNUTYPE_LONGNAME) { + char tailBuff[BLOCK_SIZE] = {0}; + size_t tailRead = fread(tailBuff, 1, BLOCK_SIZE, tarFilePtr_); + if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) { + HILOGE("Parsing tar file completed, tailBuff is empty."); + ret = 0; + } + return false; + } + // check header + if (!IsValidTarBlock(*header)) { + // when split unpack, ftell size is over than file really size [0,READ_BUFF_SIZE] + if (ftello(tarFilePtr_) > (tarFileSize_ + READ_BUFF_SIZE) || !IsEmptyBlock(buff)) { + HILOGE("Invalid tar file format"); + ret = ERR_FORMAT; + } + HILOGE("invalid tar block header"); + return false; + } + return true; +} + +std::tuple UntarFile::ParseTarFile(const string &rootPath) +{ + // re-parse tar header + rootPath_ = rootPath; + char buff[BLOCK_SIZE] = {0}; + FileStatInfo info {}; + int ret = 0; + if ((ret = CheckAndFillTarSize()) != 0) { + return {ret, {}, {}}; + } + EndFileInfo fileInfos; + ErrFileInfo errInfos; while (1) { readCnt_ = fread(buff, 1, BLOCK_SIZE, tarFilePtr_); if (readCnt_ < BLOCK_SIZE) { HILOGE("Parsing tar file completed, read data count is less then block size."); - return 0; + return {0, fileInfos, errInfos}; } TarHeader *header = reinterpret_cast(buff); - // two empty continuous block indicate end of file - if (IsEmptyBlock(buff) && header->typeFlag != GNUTYPE_LONGNAME) { - char tailBuff[BLOCK_SIZE] = {0}; - size_t tailRead = fread(tailBuff, 1, BLOCK_SIZE, tarFilePtr_); - if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) { - HILOGE("Parsing tar file completed, tailBuff is empty."); - return 0; - } + bool isValid = CheckIfTarBlockValid(buff, sizeof(buff), header, ret); + if (!isValid) { + return {ret, fileInfos, errInfos}; } - // check header - if (!IsValidTarBlock(*header)) { - // when split unpack, ftell size is over than file really size [0,READ_BUFF_SIZE] - if (ftello(tarFilePtr_) > (tarFileSize_ + READ_BUFF_SIZE) || !IsEmptyBlock(buff)) { - HILOGE("Invalid tar file format"); - ret = ERR_FORMAT; - } - HILOGE("invalid tar block header"); - return ret; + off_t fileSize = HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info); + auto result = ParseFileByTypeFlag(header->typeFlag, info); + if ((ret = DealParseTarFileResult(result, fileSize, info.fullPath, fileInfos, errInfos)) != 0) { + return {ret, fileInfos, errInfos}; } - HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info); - ParseFileByTypeFlag(header->typeFlag, info); } - return ret; + return {ret, fileInfos, errInfos}; } -int UntarFile::ParseIncrementalTarFile(const string &rootPath) +int UntarFile::DealIncreParseTarFileResult(const std::tuple &result, + const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos) { - // re-parse tar header - rootPath_ = rootPath; - char buff[BLOCK_SIZE] = {0}; - FileStatInfo info {}; - - // tarFileSize - int ret = fseeko(tarFilePtr_, 0L, SEEK_END); + auto [ret, isFilter, subErrInfo] = result; if (ret != 0) { - HILOGE("Failed to fseeko tarFile SEEK_END, err = %{public}d", errno); + HILOGE("Failed to parse incremental file by type flag"); return ret; } - tarFileSize_ = ftello(tarFilePtr_); - // reback file to begin - if ((ret = fseeko(tarFilePtr_, 0L, SEEK_SET)) != 0) { - HILOGE("Failed to fseeko tarFile SEEK_SET, err = %{public}d", errno); - return ret; + if (!isFilter) { + fileInfos[fileName] = fileSize; + if (!subErrInfo.empty()) { + errInfos.merge(subErrInfo); + } } + return 0; +} +std::tuple UntarFile::ParseIncrementalTarFile(const string &rootPath) +{ + // re-parse tar header + rootPath_ = rootPath; + char buff[BLOCK_SIZE] = {0}; + FileStatInfo info {}; + int ret = 0; + if ((ret = CheckAndFillTarSize()) != 0) { + return {ret, {}, {}}; + } + EndFileInfo fileInfos; + ErrFileInfo errFileInfo; do { readCnt_ = fread(buff, 1, BLOCK_SIZE, tarFilePtr_); if (readCnt_ < BLOCK_SIZE) { HILOGE("Parsing tar file completed, read data count is less then block size."); - return 0; + return {0, fileInfos, errFileInfo}; } TarHeader *header = reinterpret_cast(buff); - // two empty continuous block indicate end of file - if (IsEmptyBlock(buff) && header->typeFlag != GNUTYPE_LONGNAME) { - char tailBuff[BLOCK_SIZE] = {0}; - size_t tailRead = fread(tailBuff, 1, BLOCK_SIZE, tarFilePtr_); - if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) { - HILOGE("Parsing tar file completed, tailBuff is empty."); - return 0; - } - } - // check header - if (!IsValidTarBlock(*header)) { - // when split unpack, ftell size is over than file really size [0,READ_BUFF_SIZE] - if (ftello(tarFilePtr_) > (tarFileSize_ + READ_BUFF_SIZE) || !IsEmptyBlock(buff)) { - HILOGE("Invalid tar file format"); - ret = ERR_FORMAT; - } - return ret; + bool isValid = CheckIfTarBlockValid(buff, sizeof(buff), header, ret); + if (!isValid) { + return {ret, fileInfos, errFileInfo}; } - HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info); - if ((ret = ParseIncrementalFileByTypeFlag(header->typeFlag, info)) != 0) { - HILOGE("Failed to parse incremental file by type flag"); - return ret; + off_t fileSize = HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info); + auto result = ParseIncrementalFileByTypeFlag(header->typeFlag, info); + ret = DealIncreParseTarFileResult(result, fileSize, info.fullPath, fileInfos, errFileInfo); + if (ret != 0) { + return {ret, fileInfos, errFileInfo}; } } while (readCnt_ >= BLOCK_SIZE); - return ret; + return {ret, fileInfos, errFileInfo}; } -void UntarFile::ParseFileByTypeFlag(char typeFlag, FileStatInfo &info) +tuple UntarFile::ParseFileByTypeFlag(char typeFlag, FileStatInfo &info) { HILOGD("untar file: %{public}s, rootPath: %{public}s", GetAnonyPath(info.fullPath).c_str(), rootPath_.c_str()); + bool isFilter = true; + ErrFileInfo errFileInfo; switch (typeFlag) { case REGTYPE: case AREGTYPE: info.fullPath = GenRealPath(rootPath_, info.fullPath); - ParseRegularFile(info, typeFlag); + errFileInfo = ParseRegularFile(info, typeFlag); + isFilter = false; break; case SYMTYPE: break; case DIRTYPE: info.fullPath = GenRealPath(rootPath_, info.fullPath); - CreateDir(info.fullPath, info.mode); + errFileInfo = CreateDir(info.fullPath, info.mode); + isFilter = false; break; case GNUTYPE_LONGNAME: { - ReadLongName(info, tarFilePtr_, tarFileSize_); - fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET); + auto result = ReadLongName(info); + errFileInfo = std::get(result); + return {std::get(result), isFilter, errFileInfo}; break; } default: { - fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR); + if (fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR) != 0) { + HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); + return {-1, true, errFileInfo}; + } break; } } + return {0, isFilter, errFileInfo}; } -int UntarFile::ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info) +std::tuple UntarFile::ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info) { HILOGD("untar file: %{public}s, rootPath: %{public}s", GetAnonyPath(info.fullPath).c_str(), rootPath_.c_str()); string tmpFullPath = info.fullPath; + bool isFilter = true; + ErrFileInfo errFileInfo; RTrimNull(tmpFullPath); switch (typeFlag) { case REGTYPE: - case AREGTYPE: + case AREGTYPE: { if (!includes_.empty() && includes_.find(tmpFullPath) == includes_.end()) { // not in includes if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) { HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); - return -1; + return {-1, true, {}}; } break; } info.fullPath = GenRealPath(rootPath_, info.fullPath); - ParseRegularFile(info, typeFlag); + errFileInfo = ParseRegularFile(info, typeFlag); + isFilter = false; break; + } case SYMTYPE: break; case DIRTYPE: info.fullPath = GenRealPath(rootPath_, info.fullPath); - CreateDir(info.fullPath, info.mode); + errFileInfo = CreateDir(info.fullPath, info.mode); + isFilter = false; break; case GNUTYPE_LONGNAME: { - int ret = ReadLongName(info, tarFilePtr_, tarFileSize_); - if (ret != 0) { - return ret; - } - if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) { - HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); - return -1; - } + auto result = ReadLongName(info); + return {std::get(result), isFilter, std::get(result)}; break; } default: { if (fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR) != 0) { HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); - return -1; + return {-1, true, {}}; } break; } } - return 0; + return {0, isFilter, errFileInfo}; } -void UntarFile::ParseRegularFile(FileStatInfo &info, char typeFlag) +ErrFileInfo UntarFile::ParseRegularFile(FileStatInfo &info, char typeFlag) { + ErrFileInfo errFileInfo; FILE *destFile = CreateFile(info.fullPath, info.mode, typeFlag); if (destFile != nullptr) { string destStr(""); @@ -361,27 +425,32 @@ void UntarFile::ParseRegularFile(FileStatInfo &info, char typeFlag) remainSize -= readBuffSize; } fclose(destFile); - chmod(info.fullPath.data(), info.mode); + if (chmod(info.fullPath.data(), info.mode) != 0) { + HILOGE("Failed to chmod of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); + errFileInfo[info.fullPath].push_back(errno); + } struct utimbuf times; struct stat attr; if (stat(info.fullPath.c_str(), &attr) != 0) { - HILOGE("Failed to get stat of %{public}s, err = %{public}d", - GetAnonyPath(info.fullPath).c_str(), errno); + errFileInfo[info.fullPath].push_back(errno); + HILOGE("Failed to get stat of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); times.actime = info.mtime; } else { times.actime = attr.st_atime; } times.modtime = info.mtime; if (info.mtime != 0 && utime(info.fullPath.c_str(), ×) != 0) { - HILOGE("Failed to set mtime of %{public}s, err = %{public}d", - GetAnonyPath(info.fullPath).c_str(), errno); + errFileInfo[info.fullPath].push_back(errno); + HILOGE("Failed to set mtime of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); } // anyway, go to correct fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET); } else { HILOGE("Failed to create file %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); + errFileInfo[info.fullPath].push_back(errno); fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR); } + return errFileInfo; } bool UntarFile::VerifyChecksum(TarHeader &header) @@ -430,10 +499,11 @@ string UntarFile::GenRealPath(const string &rootPath, const string &realName) return realPath; } -void UntarFile::CreateDir(string &path, mode_t mode) +ErrFileInfo UntarFile::CreateDir(string &path, mode_t mode) { + ErrFileInfo errFileInfo; if (path.empty()) { - return; + return errFileInfo; } size_t len = path.length(); if (path[len - 1] == '/') { @@ -443,8 +513,10 @@ void UntarFile::CreateDir(string &path, mode_t mode) HILOGW("directory does not exist, path:%{public}s, err = %{public}d", path.c_str(), errno); if (!ForceCreateDirectoryWithMode(path, mode)) { HILOGE("Failed to force create directory %{public}s, err = %{public}d", path.c_str(), errno); + errFileInfo[path].push_back(errno); } } + return errFileInfo; } FILE *UntarFile::CreateFile(string &filePath, mode_t mode, char fileType) diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index dd3ccf163..e768d8a53 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -508,9 +508,9 @@ static NContextCBExec GetPublishFileCBExec(napi_env env, NFuncArg &funcArg, cons if (SAUtils::IsSABundleName(fileName)) { HILOGI("SA %{public}s pushlish file", bundleName.c_str()); if (fcntl(std::atoi(fileName.c_str()), F_GETFD) == -1) { - HILOGE("PublishFile fd is invalid."); - return NError(BError(BError::Codes::SDK_INVAL_ARG, "PublishFile fd is invalid.").GetCode()); - } + HILOGE("PublishFile fd is invalid."); + return NError(BError(BError::Codes::SDK_INVAL_ARG, "PublishFile fd is invalid.").GetCode()); + } return NError(entity->sessionSheet->PublishSAFile(fileInfo, UniqueFd(std::atoi(fileName.c_str())))); } return NError(entity->sessionSheet->PublishFile(fileInfo)); diff --git a/test/fuzztest/backupext_fuzzer/BUILD.gn b/test/fuzztest/backupext_fuzzer/BUILD.gn index b406dbcd5..5d32a6bd6 100644 --- a/test/fuzztest/backupext_fuzzer/BUILD.gn +++ b/test/fuzztest/backupext_fuzzer/BUILD.gn @@ -42,6 +42,7 @@ ohos_fuzztest("BackupExtFuzzTest") { "${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp", + "${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp", "${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp", "backupext_fuzzer.cpp", diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index 5b41aab97..32e37d292 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -139,6 +139,7 @@ ohos_unittest("tar_file_test") { "${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp", + "${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp", "${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp", "tar_file_test.cpp", @@ -211,6 +212,7 @@ ohos_unittest("untar_file_test") { "${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp", + "${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp", "${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp", "untar_file_test.cpp", diff --git a/tests/unittests/backup_ext/ext_extension_test.cpp b/tests/unittests/backup_ext/ext_extension_test.cpp index 7022e5e1d..993b7173d 100644 --- a/tests/unittests/backup_ext/ext_extension_test.cpp +++ b/tests/unittests/backup_ext/ext_extension_test.cpp @@ -27,6 +27,7 @@ #include "b_error/b_error.h" #include "b_error/b_excep_utils.h" #include "ext_extension.cpp" +#include "sub_ext_extension.cpp" namespace OHOS::FileManagement::Backup { using namespace std; @@ -153,8 +154,10 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0300, testing::ext::TestSize.Level try { string tarFile = " "; vector extManageInfo; - bool ret = IsUserTar(tarFile, extManageInfo); + off_t tarFileSize = 0; + bool ret = IsUserTar(tarFile, extManageInfo, tarFileSize); EXPECT_FALSE(ret); + EXPECT_TRUE(tarFileSize == 0); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction."; @@ -177,8 +180,10 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0301, testing::ext::TestSize.Level try { string tarFile = TAR_FILE; vector extManageInfo; - bool ret = IsUserTar(tarFile, extManageInfo); + off_t tarFileSize = 0; + bool ret = IsUserTar(tarFile, extManageInfo, tarFileSize); EXPECT_FALSE(ret); + EXPECT_TRUE(tarFileSize == 0); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction."; @@ -204,9 +209,12 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0302, testing::ext::TestSize.Level ExtManageInfo info; info.hashName = TAR_FILE; info.isUserTar = true; + info.sta.st_size = 1; // 1: test number; extManageInfo.push_back(info); - bool ret = IsUserTar(tarFile, extManageInfo); + off_t tarFileSize = 0; + bool ret = IsUserTar(tarFile, extManageInfo, tarFileSize); EXPECT_TRUE(ret); + EXPECT_TRUE(tarFileSize == 1); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction."; diff --git a/tests/unittests/backup_ext/untar_file_test.cpp b/tests/unittests/backup_ext/untar_file_test.cpp index 9d79edb43..13a425214 100644 --- a/tests/unittests/backup_ext/untar_file_test.cpp +++ b/tests/unittests/backup_ext/untar_file_test.cpp @@ -108,7 +108,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0100, testing::ext::TestSize.Lev try { string tarFile(""); string rootPath(""); - int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath); + auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath); EXPECT_EQ(ret, ENOENT); ClearCache(); } catch (...) { @@ -151,7 +151,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0200, testing::ext::TestSize.Lev GTEST_LOG_(INFO) << " execute tar failure, errno :" << errno; throw BError(errno); } - int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath); + auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath); EXPECT_EQ(ret, 0); ClearCache(); } catch (...) { @@ -186,7 +186,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0300, testing::ext::TestSize.Lev SaveStringToFile(aFile, "hello"); string rootPath(root); - int ret = UntarFile::GetInstance().UnPacket(aFile, rootPath); + auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(aFile, rootPath); EXPECT_EQ(ret, 0); ClearCache(); } catch (...) { @@ -225,7 +225,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0400, testing::ext::TestSize.Lev } string rootPath(root); - int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath); + auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath); EXPECT_EQ(ret, 0); ClearCache(); } catch (...) { @@ -276,7 +276,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0500, testing::ext::TestSize.Lev TarFile::GetInstance().Packet(smallFiles, "test", root, tarMap); string rootPath(root); - int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath); + auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath); EXPECT_EQ(ret, 0); ClearCache(); } catch (...) { @@ -328,7 +328,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0100, testing::ext::T string tarFile = root + "/test.0.tar"; string rootPath(root); unordered_map cloudFiles; - int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); + auto [ret, fileInfos, errFileInfos] = + UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); EXPECT_EQ(ret, 0); ClearCache(); } catch (...) { @@ -358,7 +359,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0200, testing::ext::T string tarFile = root + "/empty.0.tar"; string rootPath(root); unordered_map cloudFiles; - int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); + auto [ret, fileInfos, errFileInfos] = + UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); EXPECT_EQ(ret, 2); // 错误码2表示找不到文件或路径 ClearCache(); } catch (...) { @@ -404,7 +406,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0300, testing::ext::T FILE *currentTarFile = fopen(tarFile.c_str(), "wb+"); fwrite("\0", sizeof(uint8_t), 1, currentTarFile); fclose(currentTarFile); - int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); + auto [ret, fileInfos, errFileInfos] = + UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); EXPECT_EQ(ret, 0); ClearCache(); } catch (...) { @@ -461,7 +464,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0400, testing::ext::T fseeko(currentTarFile, 1L, SEEK_SET); fwrite("\0", sizeof(uint8_t), 1, currentTarFile); fclose(currentTarFile); - int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); + auto [ret, fileInfos, errFileInfos] = + UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles); EXPECT_EQ(ret, 0); ClearCache(); } catch (...) { diff --git a/tests/unittests/backup_utils/b_error/b_error_test.cpp b/tests/unittests/backup_utils/b_error/b_error_test.cpp index 027edb739..7a77a1791 100644 --- a/tests/unittests/backup_utils/b_error/b_error_test.cpp +++ b/tests/unittests/backup_utils/b_error/b_error_test.cpp @@ -485,7 +485,7 @@ HWTEST_F(BErrorTest, b_error_GetCodeByErrno_0200, testing::ext::TestSize.Level0) GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCodeByErrno_0200"; int32_t errnoSys = EPERM; int result = BError::GetCodeByErrno(errnoSys); - EXPECT_EQ(result, BError::BackupErrorCode::E_IPCSS); + EXPECT_EQ(result, BError::BackupErrorCode::E_PERM); GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCodeByErrno_0200"; } diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index e3e729ca2..478328a7e 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -104,6 +104,17 @@ public: * @return 拼接结果 */ static std::string BuildBundleNameIndexInfo(const std::string &bundleName, int bundleIndex); + + /** + * @brief 组建恢复文件错误信息的json + * + * @param jsonStr 组建结果 + * @param errCode 错误码 + * + * @return 是否组建成功 + * + */ + static bool BuildRestoreErrInfo(std::string &jsonStr, std::map> errFileInfo); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_ohos/startup/backup_para.h b/utils/include/b_ohos/startup/backup_para.h index 1cdf80737..c5c6ef481 100644 --- a/utils/include/b_ohos/startup/backup_para.h +++ b/utils/include/b_ohos/startup/backup_para.h @@ -49,6 +49,13 @@ public: * @return 获取的配置项backup.overrideIncrementalRestore的值为true时则返回true,否则返回false */ bool GetBackupOverrideIncrementalRestore(); + + /** + * @brief 获取backup.para配置项backupDebugState的值 + * + * @return 获取的配置项backup.backupDebugState的值为true时则返回true,否则返回false + */ + static bool GetBackupDebugState(); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index d99581d28..32e5932b5 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -260,5 +260,4 @@ vector BDir::GetDirs(const vector &paths) vector dirs(inc.begin(), inc.end()); return dirs; } - } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index b50042c1c..220b9c6a4 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -201,4 +201,41 @@ std::string BJsonUtil::BuildBundleNameIndexInfo(const std::string &bundleName, i result += std::to_string(appIndex); return result; } + +bool BJsonUtil::BuildRestoreErrInfo(std::string &jsonStr, std::map> errFileInfo) +{ + cJSON *errJson = cJSON_CreateObject(); + if (errJson == nullptr) { + HILOGE("Creat json failed"); + return false; + } + cJSON *arrJson = cJSON_CreateArray(); + if (arrJson == nullptr) { + cJSON_Delete(errJson); + return false; + } + for (const auto &it : errFileInfo) { + for (const auto &codeIt : it.second) { + cJSON *eleJson = cJSON_CreateObject(); + if (eleJson == nullptr) { + HILOGE("Creat eleJson failed"); + continue; + } + cJSON_AddStringToObject(eleJson, "type", "ErrorInfo"); + cJSON_AddStringToObject(eleJson, "errorInfo", it.first.c_str()); + cJSON_AddNumberToObject(eleJson, "errorCode", codeIt); + cJSON_AddItemToArray(arrJson, eleJson); + } + } + cJSON_AddItemToObject(errJson, "resultInfo", arrJson); + char *data = cJSON_Print(errJson); + if (data == nullptr) { + cJSON_Delete(errJson); + return false; + } + jsonStr = std::string(data); + cJSON_Delete(errJson); + cJSON_free(data); + return true; +} } \ No newline at end of file diff --git a/utils/src/b_ohos/startup/backup_para.cpp b/utils/src/b_ohos/startup/backup_para.cpp index 46754c5dc..a9df69780 100644 --- a/utils/src/b_ohos/startup/backup_para.cpp +++ b/utils/src/b_ohos/startup/backup_para.cpp @@ -27,7 +27,7 @@ namespace OHOS::FileManagement::Backup { using namespace std; - +const char* BACKUP_DEBUG_STATE = "sys.backup.check.enable"; /** * @brief 获取配置参数的值 * @@ -104,4 +104,16 @@ tuple BackupPara::GetBackupDebugOverrideAccount() } return {false, 0}; } + +bool BackupPara::GetBackupDebugState() +{ + char paraValue[30] = {0}; // 30: for system paramter + auto res = GetParameter(BACKUP_DEBUG_STATE, "-1", paraValue, sizeof(paraValue)); + if (res <= 0) { + HILOGE("GetParameter fail, key:%{public}s res:%{public}d", BACKUP_DEBUG_STATE, res); + return false; + } + std::string result(paraValue); + return result == "true"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From d3938100433473153320bca003254bd9a87fc54b Mon Sep 17 00:00:00 2001 From: Clone_Zhang Date: Fri, 16 Aug 2024 20:05:57 +0800 Subject: [PATCH 48/53] fix:timeout strategy Signed-off-by: Clone_Zhang --- .../native/backup_ext/include/ext_extension.h | 30 +- .../native/backup_ext/src/ext_extension.cpp | 285 ++++-------------- .../backup_ext/src/sub_ext_extension.cpp | 236 +++++++++++++++ .../backup_kit_inner/src/service_proxy.cpp | 44 +++ .../native/backup_kit_inner/impl/i_service.h | 2 + .../impl/i_service_ipc_interface_code.h | 2 + .../backup_kit_inner/impl/service_proxy.h | 2 + .../kits/js/backup/prop_n_operation.cpp | 4 +- .../backup_sa/include/module_ipc/service.h | 10 + .../include/module_ipc/service_stub.h | 2 + .../include/module_ipc/svc_session_manager.h | 54 +++- services/backup_sa/src/module_ipc/service.cpp | 148 ++++++--- .../src/module_ipc/service_incremental.cpp | 6 +- .../backup_sa/src/module_ipc/service_stub.cpp | 36 +++ .../src/module_ipc/svc_session_manager.cpp | 125 ++++++-- .../backup_kit_inner/service_proxy_mock.cpp | 9 + tests/mock/module_ipc/service_mock.cpp | 10 + .../module_ipc/svc_session_manager_mock.cpp | 20 +- .../svc_session_manager_throw_mock.cpp | 24 +- .../svc_session_manager_throw_mock.h | 12 +- .../backup_impl/include/i_service_mock.h | 10 + .../module_ipc/service_stub_test.cpp | 2 + .../module_ipc/service_throw_test.cpp | 71 +---- .../module_ipc/svc_session_manager_test.cpp | 114 +++---- .../backup_sa/session/service_proxy_mock.cpp | 10 + utils/BUILD.gn | 1 + utils/include/b_resources/b_constants.h | 1 + utils/include/b_sa/b_sa_utils.h | 2 +- utils/include/b_utils/b_time.h | 28 ++ utils/src/b_utils/b_time.cpp | 40 +++ 30 files changed, 881 insertions(+), 459 deletions(-) create mode 100644 utils/include/b_utils/b_time.h create mode 100644 utils/src/b_utils/b_time.cpp diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index f74b25bb0..1c8ed889a 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -170,6 +170,20 @@ private: */ void AppIncrementalDone(ErrCode errCode); + /** + * @brief start extension timer by ipc + * + * @param result + */ + void StartExtTimer(bool &isExtStart); + + /** + * @brief start fwk timer by ipc + * + * @param errCode + */ + void StartFwkTimer(bool &isFwkStart); + /** * @brief get callbackEx for execute onRestore * @@ -178,12 +192,26 @@ private: std::function RestoreResultCallbackEx(wptr obj); /** - * @brief get callbackEx for execute onRestore with string param + * @brief get increCallbackEx for execute onRestore with string param * * @param errCode */ std::function IncRestoreResultCallbackEx(wptr obj); + /** + * @brief get increCallback for execute onRestore with string param + * + * @param errCode + */ + std::function IncRestoreResultCallback(wptr obj); + + /** + * @brief get callback for execute onRestore with string param + * + * @param errCode + */ + std::function RestoreResultCallback(wptr obj); + /** * @brief get callbackEx for execute onRestore * diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 3ab7acc64..a86396d42 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -785,6 +785,14 @@ void BackupExtExtension::AsyncTaskBackup(const string config) auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); try { + HILOGI("Do backup, start fwk timer begin."); + bool isFwkStart; + ptr->StartFwkTimer(isFwkStart); + if (!isFwkStart) { + HILOGE("Do backup, start fwk timer fail."); + return; + } + HILOGI("Do backup, start fwk timer end."); BJsonCachedEntity cachedEntity(config); auto cache = cachedEntity.Structuralize(); auto ret = ptr->DoBackup(cache); @@ -1260,26 +1268,19 @@ void BackupExtExtension::AsyncTaskRestoreForUpgrade() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto task = [obj {wptr(this)}]() { - auto callBackup = [obj](ErrCode errCode, std::string errMsg) { - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - HILOGI("Current bundle will execute app done"); - if (errMsg.empty()) { - extensionPtr->AppDone(errCode); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); - } - extensionPtr->DoClear(); - }; auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { + HILOGI("On restore, start ext timer begin."); + bool isExtStart; + ptr->StartExtTimer(isExtStart); + if (!isExtStart) { + HILOGE("On restore, start ext timer fail."); + return; + } + HILOGI("On restore, start ext timer end."); + auto callBackup = ptr->RestoreResultCallback(obj); auto callBackupEx = ptr->RestoreResultCallbackEx(obj); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); if (err != ERR_OK) { @@ -1317,26 +1318,19 @@ void BackupExtExtension::ExtClear() void BackupExtExtension::AsyncTaskIncrementalRestoreForUpgrade() { auto task = [obj {wptr(this)}]() { - auto callBackup = [obj](ErrCode errCode, std::string errMsg) { - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - HILOGI("Current bundle will execute app done"); - if (errMsg.empty()) { - extensionPtr->AppIncrementalDone(errCode); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); - } - extensionPtr->DoClear(); - }; auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { + HILOGI("On incrementalRestore, start ext timer begin."); + bool isExtStart; + ptr->StartExtTimer(isExtStart); + if (!isExtStart) { + HILOGE("On incrementalRestore, start ext timer fail."); + return; + } + HILOGI("On incrementalRestore, start ext timer end."); + auto callBackup = ptr->IncRestoreResultCallback(obj); auto callBackupEx = ptr->IncRestoreResultCallbackEx(obj); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); if (err != ERR_OK) { @@ -1427,6 +1421,28 @@ void BackupExtExtension::AppResultReport(const std::string restoreRetInfo, } } +void BackupExtExtension::StartExtTimer(bool &isExtStart) +{ + auto proxy = ServiceProxy::GetInstance(); + BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + HILOGI("Start ext timer by ipc."); + auto ret = proxy->StartExtTimer(isExtStart); + if (ret != ERR_OK) { + HILOGE("Start ext timer failed, errCode: %{public}d", ret); + } +} + +void BackupExtExtension::StartFwkTimer(bool &isFwkStart) +{ + auto proxy = ServiceProxy::GetInstance(); + BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + HILOGI("Start fwk timer by ipc."); + auto ret = proxy->StartFwkTimer(isFwkStart); + if (ret != ERR_OK) { + HILOGE("Start fwk timer failed, errCode: %{public}d", ret); + } +} + void BackupExtExtension::AsyncTaskOnBackup() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -1773,7 +1789,14 @@ ErrCode BackupExtExtension::IncrementalBigFileReady(const TarMap &pkgInfo, void BackupExtExtension::AsyncTaskDoIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) { - HILOGI("Start AsyncTaskDoIncrementalBackup"); + HILOGI("Do IncrementalBackup, start fwk timer begin."); + bool isFwkStart; + StartFwkTimer(isFwkStart); + if (!isFwkStart) { + HILOGE("Do IncrementalBackup, start fwk timer fail."); + return; + } + HILOGI("Do IncrementalBackup, start fwk timer end."); int incrementalFdDup = dup(incrementalFd); int manifestFdDup = dup(manifestFd); if (incrementalFdDup < 0) { @@ -1989,200 +2012,4 @@ int BackupExtExtension::DoIncrementalBackup(const vector smallFiles.size(), allFiles.size()); return err; } - -void BackupExtExtension::AppIncrementalDone(ErrCode errCode) -{ - HILOGI("Begin"); - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - HILOGE("Failed to obtain the ServiceProxy handle"); - DoClear(); - return; - } - auto ret = proxy->AppIncrementalDone(errCode); - if (ret != ERR_OK) { - HILOGE("Failed to notify the app done. err = %{public}d", ret); - } -} - -ErrCode BackupExtExtension::GetBackupInfo(std::string &result) -{ - auto obj = wptr(this); - auto ptr = obj.promote(); - if (ptr == nullptr) { - HILOGE("Failed to get ext extension."); - return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); - } - if (ptr->extension_ == nullptr) { - HILOGE("Failed to get extension."); - return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); - } - auto callBackup = [ptr](ErrCode errCode, const std::string result) { - if (ptr == nullptr) { - HILOGE("Failed to get ext extension."); - return; - } - HILOGI("GetBackupInfo callBackup start. result = %{public}s", result.c_str()); - ptr->backupInfo_ = result; - }; - auto ret = ptr->extension_->GetBackupInfo(callBackup); - if (ret != ERR_OK) { - HILOGE("Failed to get backupInfo. err = %{public}d", ret); - return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); - } - HILOGD("backupInfo = %s", backupInfo_.c_str()); - result = backupInfo_; - backupInfo_.clear(); - - return ERR_OK; -} - -ErrCode BackupExtExtension::UpdateFdSendRate(std::string &bundleName, int32_t sendRate) -{ - try { - std::lock_guard lock(updateSendRateLock_); - HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); - VerifyCaller(); - bundleName_ = bundleName; - sendRate_ = sendRate; - if (sendRate > 0) { - startSendFdRateCon_.notify_one(); - } - return ERR_OK; - } catch (...) { - HILOGE("Failed to UpdateFdSendRate"); - return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); - } -} - -std::function BackupExtExtension::RestoreResultCallbackEx(wptr obj) -{ - HILOGI("Begin get callbackEx"); - return [obj](ErrCode errCode, const std::string restoreRetInfo) { - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); - if (errCode == ERR_OK) { - if (restoreRetInfo.size()) { - HILOGI("Will notify restore result report"); - extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::FULL_RESTORE); - } - return; - } - if (restoreRetInfo.empty()) { - extensionPtr->AppDone(errCode); - extensionPtr->DoClear(); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, restoreRetInfo); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); - extensionPtr->DoClear(); - } - }; -} - -std::function BackupExtExtension::AppDoneCallbackEx(wptr obj) -{ - HILOGI("Begin get callback for appDone"); - return [obj](ErrCode errCode, std::string errMsg) { - HILOGI("begin call callBackupExAppDone"); - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - extensionPtr->AppDone(errCode); - extensionPtr->DoClear(); - }; -} - -std::function BackupExtExtension::IncRestoreResultCallbackEx(wptr obj) -{ - HILOGI("Begin get callback for onRestore"); - return [obj](ErrCode errCode, const std::string restoreRetInfo) { - HILOGI("begin call restoreEx"); - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); - if (errCode == ERR_OK) { - if (restoreRetInfo.size()) { - extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::INCREMENTAL_RESTORE); - } - return; - } - if (restoreRetInfo.empty()) { - extensionPtr->AppIncrementalDone(errCode); - extensionPtr->DoClear(); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, restoreRetInfo); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); - extensionPtr->DoClear(); - } - }; -} - -std::function BackupExtExtension::HandleBackupEx(wptr obj) -{ - HILOGI("Begin get HandleBackupEx"); - return [obj](ErrCode errCode, const std::string backupExRetInfo) { - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); - } - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); - if (backupExRetInfo.size()) { - HILOGI("Start GetAppLocalListAndDoIncrementalBackup"); - proxy->GetAppLocalListAndDoIncrementalBackup(); - HILOGI("Will notify backup result report"); - extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::INCREMENTAL_BACKUP); - } - }; -} - -std::function BackupExtExtension::HandleTaskBackupEx(wptr obj) -{ - HILOGI("Begin get HandleTaskBackupEx"); - return [obj](ErrCode errCode, const std::string backupExRetInfo) { - HILOGI("begin call backup"); - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); - if (backupExRetInfo.size()) { - extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig()); - HILOGI("Will notify backup result report"); - extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::FULL_BACKUP); - } - }; -} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index 888d44c6e..29786a9dd 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -172,4 +172,240 @@ tuple> BackupExtExtension::CheckRestoreFileInfos() } return {true, errFiles}; } + +void BackupExtExtension::AppIncrementalDone(ErrCode errCode) +{ + HILOGI("Begin"); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGE("Failed to obtain the ServiceProxy handle"); + DoClear(); + return; + } + auto ret = proxy->AppIncrementalDone(errCode); + if (ret != ERR_OK) { + HILOGE("Failed to notify the app done. err = %{public}d", ret); + } +} + +ErrCode BackupExtExtension::GetBackupInfo(std::string &result) +{ + auto obj = wptr(this); + auto ptr = obj.promote(); + if (ptr == nullptr) { + HILOGE("Failed to get ext extension."); + return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + } + if (ptr->extension_ == nullptr) { + HILOGE("Failed to get extension."); + return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + } + auto callBackup = [ptr](ErrCode errCode, const std::string result) { + if (ptr == nullptr) { + HILOGE("Failed to get ext extension."); + return; + } + HILOGI("GetBackupInfo callBackup start. result = %{public}s", result.c_str()); + ptr->backupInfo_ = result; + }; + auto ret = ptr->extension_->GetBackupInfo(callBackup); + if (ret != ERR_OK) { + HILOGE("Failed to get backupInfo. err = %{public}d", ret); + return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + } + HILOGD("backupInfo = %s", backupInfo_.c_str()); + result = backupInfo_; + backupInfo_.clear(); + + return ERR_OK; +} + +ErrCode BackupExtExtension::UpdateFdSendRate(std::string &bundleName, int32_t sendRate) +{ + try { + std::lock_guard lock(updateSendRateLock_); + HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); + VerifyCaller(); + bundleName_ = bundleName; + sendRate_ = sendRate; + if (sendRate > 0) { + startSendFdRateCon_.notify_one(); + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to UpdateFdSendRate"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); + } +} + +std::function BackupExtExtension::RestoreResultCallbackEx(wptr obj) +{ + HILOGI("Begin get callbackEx"); + return [obj](ErrCode errCode, const std::string restoreRetInfo) { + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); + if (errCode == ERR_OK) { + if (restoreRetInfo.size()) { + HILOGI("Will notify restore result report"); + extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::FULL_RESTORE); + } + return; + } + if (restoreRetInfo.empty()) { + extensionPtr->AppDone(errCode); + extensionPtr->DoClear(); + } else { + std::string errInfo; + BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, restoreRetInfo); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); + extensionPtr->DoClear(); + } + }; +} + +std::function BackupExtExtension::AppDoneCallbackEx(wptr obj) +{ + HILOGI("Begin get callback for appDone"); + return [obj](ErrCode errCode, std::string errMsg) { + HILOGI("begin call callBackupExAppDone"); + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + extensionPtr->AppDone(errCode); + extensionPtr->DoClear(); + }; +} + +std::function BackupExtExtension::IncRestoreResultCallbackEx(wptr obj) +{ + HILOGI("Begin get callback for onRestore"); + return [obj](ErrCode errCode, const std::string restoreRetInfo) { + HILOGI("begin call restoreEx"); + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); + if (errCode == ERR_OK) { + if (restoreRetInfo.size()) { + extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::INCREMENTAL_RESTORE); + } + return; + } + if (restoreRetInfo.empty()) { + extensionPtr->AppIncrementalDone(errCode); + extensionPtr->DoClear(); + } else { + std::string errInfo; + BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, restoreRetInfo); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); + extensionPtr->DoClear(); + } + }; +} + +std::function BackupExtExtension::IncRestoreResultCallback(wptr obj) +{ + return [obj](ErrCode errCode, std::string errMsg) { + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + HILOGI("Current bundle will execute app done"); + if (errMsg.empty()) { + extensionPtr->AppIncrementalDone(errCode); + } else { + std::string errInfo; + BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); + } + extensionPtr->DoClear(); + }; +} + +std::function BackupExtExtension::RestoreResultCallback(wptr obj) +{ + return [obj](ErrCode errCode, std::string errMsg) { + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + HILOGI("Current bundle will execute app done"); + if (errMsg.empty()) { + extensionPtr->AppDone(errCode); + } else { + std::string errInfo; + BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); + } + extensionPtr->DoClear(); + }; +} + +std::function BackupExtExtension::HandleBackupEx(wptr obj) +{ + HILOGI("Begin get HandleBackupEx"); + return [obj](ErrCode errCode, const std::string backupExRetInfo) { + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + } + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); + if (backupExRetInfo.size()) { + HILOGI("Start GetAppLocalListAndDoIncrementalBackup"); + proxy->GetAppLocalListAndDoIncrementalBackup(); + HILOGI("Will notify backup result report"); + extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::INCREMENTAL_BACKUP); + } + }; +} + +std::function BackupExtExtension::HandleTaskBackupEx(wptr obj) +{ + HILOGI("Begin get HandleTaskBackupEx"); + return [obj](ErrCode errCode, const std::string backupExRetInfo) { + HILOGI("begin call backup"); + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); + if (backupExRetInfo.size()) { + extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig()); + HILOGI("Will notify backup result report"); + extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::FULL_BACKUP); + } + }; +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 1d004e4f1..0187729c3 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -585,4 +585,48 @@ ErrCode ServiceProxy::UpdateSendRate(std::string &bundleName, int32_t sendRate, HILOGI("ServiceProxy UpdateSendRate end. ret = %{public}d", ret); return BError(BError::Codes::OK, "success"); } + +ErrCode ServiceProxy::StartExtTimer(bool &isExtStart) +{ + HILOGI("ServiceProxy StartExtTimer Begin."); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()->SendRequest(static_cast(IServiceInterfaceCode::SERVICE_CMD_START_EXT_TIMER), + data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + reply.ReadBool(isExtStart); + HILOGI("ServiceProxy StartExtTimer end. isExtStart = %d", isExtStart); + return BError(BError::Codes::OK, "success"); +} + +ErrCode ServiceProxy::StartFwkTimer(bool &isFwkStart) +{ + HILOGI("ServiceProxy StartFwkTimer Begin."); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()->SendRequest(static_cast(IServiceInterfaceCode::SERVICE_CMD_START_FWK_TIMER), + data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + reply.ReadBool(isFwkStart); + HILOGI("ServiceProxy StartFwkTimer end. isFwkStart = %d", isFwkStart); + return BError(BError::Codes::OK, "success"); +} } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h index 49348fb58..6e7b7d4c7 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h @@ -85,6 +85,8 @@ public: virtual ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) = 0; virtual ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) = 0; virtual ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) = 0; + virtual ErrCode StartExtTimer(bool &isExtStart) = 0; + virtual ErrCode StartFwkTimer(bool &isFwkStart) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Backup.IService") }; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h index 1de4b9c45..f8dfcc679 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h @@ -45,6 +45,8 @@ enum class IServiceInterfaceCode { SERVICE_CMD_GET_INCREMENTAL_FILE_NAME, SERVICE_CMD_GET_BACKUP_INFO, SERVICE_CMD_UPDATE_TIMER, + SERVICE_CMD_START_EXT_TIMER, + SERVICE_CMD_START_FWK_TIMER, SERVICE_CMD_UPDATE_SENDRATE, SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP, }; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h index d0845087e..9eab1671e 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h @@ -68,6 +68,8 @@ public: ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) override; ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override; ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override; + ErrCode StartExtTimer(bool &isExtStart) override; + ErrCode StartFwkTimer(bool &isFwkStart) override; public: explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} diff --git a/interfaces/kits/js/backup/prop_n_operation.cpp b/interfaces/kits/js/backup/prop_n_operation.cpp index 593c67a59..6e27a0700 100644 --- a/interfaces/kits/js/backup/prop_n_operation.cpp +++ b/interfaces/kits/js/backup/prop_n_operation.cpp @@ -31,8 +31,6 @@ namespace OHOS::FileManagement::Backup { using namespace std; using namespace LibN; -const int32_t H_TO_MS = 3600 * 1000; - static napi_value AsyncCallback(napi_env env, const NFuncArg& funcArg) { HILOGD("called LocalCapabilities::AsyncCallback begin"); @@ -311,7 +309,7 @@ napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) } NVal jsBundleInt(env, funcArg[NARG_POS::SECOND]); auto [succInt, time] = jsBundleInt.ToInt32(); - if (!succInt || time <= 0 || time > H_TO_MS) { + if (!succInt || time <= 0 || time > static_cast(BConstants::H2MS)) { HILOGE("Second argument is not number."); NError(E_PARAMS).ThrowErr(env); return nullptr; diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 45a9393e5..2eba65653 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -77,6 +77,8 @@ public: ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) override; ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override; ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override; + ErrCode StartExtTimer(bool &isExtStart) override; + ErrCode StartFwkTimer(bool &isFwkStart) override; ErrCode SAResultReport(const std::string bundleName, const std::string resultInfo, const ErrCode errCode, const BackupRestoreScenario sennario); @@ -227,6 +229,14 @@ public: */ std::function GetBackupInfoConnectDied(wptr obj, std::string &bundleName); + /** + * @brief timeout callback + * + * @param ptr 当前对象 + * @param bundleName 应用名称 + */ + std::function TimeOutCallback(wptr ptr, std::string bundleName); + public: explicit Service(int32_t saID, bool runOnCreate = false) : SystemAbility(saID, runOnCreate) { diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h index bd40fdd1e..564b4539c 100644 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ b/services/backup_sa/include/module_ipc/service_stub.h @@ -62,6 +62,8 @@ private: int32_t CmdGetBackupInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdUpdateTimer(MessageParcel &data, MessageParcel &reply); int32_t CmdUpdateSendRate(MessageParcel &data, MessageParcel &reply); + int32_t CmdStartExtTimer(MessageParcel &data, MessageParcel &reply); + int32_t CmdStartFwkTimer(MessageParcel &data, MessageParcel &reply); void ServiceStubSupplement(); void ServiceStubSuppAppendBundles(); diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h index 7baf1cabb..676d2d205 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -56,9 +56,12 @@ struct BackupExtInfo { /* Clone App: old device app versionCode */ std::string versionName; /* Ext Ability APP process time */ - uint32_t extTimerId; + uint32_t timerId; /* Timer Status: true is start & false is stop */ - bool timerStatus {false}; + bool extTimerStatus {false}; + bool fwkTimerStatus {false}; + uint32_t timeCount; + uint32_t startTime; int64_t dataSize; int64_t lastIncrementalTime; int32_t manifestFd; @@ -384,12 +387,39 @@ public: void SetBundleDataSize(const std::string &bundleName, int64_t dataSize); /** - * @brief 启动应用扩展能力定时器 + * @brief 启动框架定时器 * * @param bundleName 应用名称 - * @return + * @param callback 超时回调 + * @return bool + */ + bool StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback); + + /** + * @brief 停止框架定时器 + * + * @param bundleName 应用名称 + * @param callback 超时回调 + * @return bool + */ + bool StopFwkTimer(const std::string &bundleName); + + /** + * @brief 启动extension定时器 + * + * @param bundleName 应用名称 + * @param callback 超时回调 + * @return bool */ - void BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback); + bool StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback); + + /** + * @brief 停止extension定时器 + * + * @param bundleName 应用名称 + * @return bool + */ + bool StopExtTimer(const std::string &bundleName); /** * @brief 重新设置定时器 @@ -402,14 +432,6 @@ public: bool UpdateTimer(const std::string &bundleName, uint32_t timeOut, const Utils::Timer::TimerCallback &callback); - /** - * @brief 取消/暂停应用扩展能力定时器 - * - * @param bundleName 应用名称 - * @return - */ - void BundleExtTimerStop(const std::string &bundleName); - /** * @brief sessionCnt加计数 * @@ -532,11 +554,11 @@ public: */ explicit SvcSessionManager(wptr reversePtr) : reversePtr_(reversePtr) { - extBundleTimer.Setup(); + timer_.Setup(); } ~SvcSessionManager() override { - extBundleTimer.Shutdown(); + timer_.Shutdown(); } private: @@ -545,7 +567,7 @@ private: sptr deathRecipient_; Impl impl_; uint32_t extConnectNum_ {0}; - Utils::Timer extBundleTimer {"backupBundleExtTimer"}; + Utils::Timer timer_ {"backupTimer"}; std::atomic sessionCnt_ {0}; bool unloadSAFlag_ {false}; int32_t memoryParaCurSize_ {BConstants::DEFAULT_VFS_CACHE_PRESSURE}; diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 8f65b2178..2cdd68162 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -745,7 +745,8 @@ ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd, int32_t errCo // 通知extension清空缓存 proxy->HandleClear(); // 清除Timer - session_->BundleExtTimerStop(callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); // 通知TOOL 备份完成 session_->GetServiceReverseProxy()->BackupOnBundleFinished(BError(BError::Codes::OK), callerName); // 断开extension @@ -786,7 +787,8 @@ ErrCode Service::AppDone(ErrCode errCode) throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } proxy->HandleClear(); - session_->BundleExtTimerStop(callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); NotifyCallerCurAppDone(errCode, callerName); backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); @@ -863,7 +865,8 @@ void Service::NotifyCloneBundleFinish(std::string bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } proxy->HandleClear(); - session_->BundleExtTimerStop(bundleName); + session_->StopFwkTimer(bundleName); + session_->StopExtTimer(bundleName); backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(bundleName); } @@ -1048,7 +1051,8 @@ void Service::ExtConnectDied(const string &callName) try { HILOGI("Begin, bundleName: %{public}s", callName.c_str()); /* Clear Timer */ - session_->BundleExtTimerStop(callName); + session_->StopFwkTimer(callName); + session_->StopExtTimer(callName); auto backUpConnection = session_->GetExtConnection(callName); if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) { backUpConnection->DisconnectBackupExtAbility(); @@ -1193,44 +1197,15 @@ void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) void Service::ExtConnectDone(string bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - auto timeoutCallback = [ptr {wptr(this)}, bundleName]() { - HILOGI("begin timeoutCallback bundleName = %{public}s", bundleName.c_str()); - auto thisPtr = ptr.promote(); - if (!thisPtr) { - HILOGE("ServicePtr is nullptr."); - return; - } - auto sessionPtr = ptr->session_; - if (sessionPtr == nullptr) { - HILOGE("SessionPtr is nullptr."); - return; - } - try { - if (SAUtils::IsSABundleName(bundleName)) { - auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName); - shared_ptr saConnection = sessionConnection.lock(); - if (saConnection == nullptr) { - HILOGE("lock sa connection ptr is nullptr"); - return; - } - sessionPtr->BundleExtTimerStop(bundleName); - saConnection->DisconnectBackupSAExt(); - } else { - auto sessionConnection = sessionPtr->GetExtConnection(bundleName); - sessionPtr->BundleExtTimerStop(bundleName); - sessionConnection->DisconnectBackupExtAbility(); - } - thisPtr->ClearSessionAndSchedInfo(bundleName); - thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); - } catch (...) { - HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); - thisPtr->ClearSessionAndSchedInfo(bundleName); - thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); - } - }; try { HILOGE("begin %{public}s", bundleName.data()); - session_->BundleExtTimerStart(bundleName, timeoutCallback); + auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); + auto scenario = session_->GetScenario(); + if (scenario == IServiceReverse::Scenario::BACKUP) { + session_->StartExtTimer(bundleName, timeoutCallback); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + session_->StartFwkTimer(bundleName, timeoutCallback); + } session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::RUNNING); sched_->Sched(bundleName); } catch (...) { @@ -1574,6 +1549,54 @@ ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result) } } +ErrCode Service::StartExtTimer(bool &isExtStart) +{ + try { + HILOGI("Service::StartExtTimer begin."); + string bundleName = VerifyCallerAndGetCallerName(); + if (session_ == nullptr) { + HILOGE("StartExtTimer error, session_ is nullptr."); + isExtStart = false; + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(); + auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); + session_->StopFwkTimer(bundleName); + isExtStart = session_->StartExtTimer(bundleName, timeoutCallback); + session_->DecreaseSessionCnt(); + return BError(BError::Codes::OK); + } catch (...) { + isExtStart = false; + session_->DecreaseSessionCnt(); + HILOGI("Unexpected exception"); + return EPERM; + } +} + +ErrCode Service::StartFwkTimer(bool &isFwkStart) +{ + try { + HILOGI("Service::StartFwkTimer begin."); + string bundleName = VerifyCallerAndGetCallerName(); + if (session_ == nullptr) { + HILOGE("StartFwkTimer error, session_ is nullptr."); + isFwkStart = false; + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(); + auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); + session_->StopExtTimer(bundleName); + isFwkStart = session_->StartFwkTimer(bundleName, timeoutCallback); + session_->DecreaseSessionCnt(); + return BError(BError::Codes::OK); + } catch (...) { + isFwkStart = false; + session_->DecreaseSessionCnt(); + HILOGI("Unexpected exception"); + return EPERM; + } +} + ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) { auto timeoutCallback = [ptr {wptr(this)}, bundleName]() { @@ -1590,7 +1613,8 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res } try { auto sessionConnection = sessionPtr->GetExtConnection(bundleName); - sessionPtr->BundleExtTimerStop(bundleName); + sessionPtr->StopFwkTimer(bundleName); + sessionPtr->StopExtTimer(bundleName); sessionConnection->DisconnectBackupExtAbility(); thisPtr->ClearSessionAndSchedInfo(bundleName); thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); @@ -1722,7 +1746,8 @@ ErrCode Service::SADone(ErrCode errCode, std::string bundleName) HILOGE("lock sa connection ptr is nullptr"); return BError(BError::Codes::SA_INVAL_ARG); } - session_->BundleExtTimerStop(bundleName); + session_->StopFwkTimer(bundleName); + session_->StopExtTimer(bundleName); saConnection->DisconnectBackupSAExt(); ClearSessionAndSchedInfo(bundleName); } @@ -1765,4 +1790,43 @@ void Service::NotifyCallerCurAppDone(ErrCode errCode, const std::string &callerN session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, callerName); } } + +std::function Service::TimeOutCallback(wptr ptr, std::string bundleName) +{ + return [ptr, bundleName]() { + HILOGI("begin timeoutCallback bundleName = %{public}s", bundleName.c_str()); + auto thisPtr = ptr.promote(); + if (!thisPtr) { + HILOGE("ServicePtr is nullptr."); + return; + } + auto sessionPtr = thisPtr->session_; + if (sessionPtr == nullptr) { + HILOGE("SessionPtr is nullptr."); + return; + } + try { + if (SAUtils::IsSABundleName(bundleName)) { + auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName); + shared_ptr saConnection = sessionConnection.lock(); + if (saConnection == nullptr) { + HILOGE("lock sa connection ptr is nullptr"); + return; + } + saConnection->DisconnectBackupSAExt(); + } else { + auto sessionConnection = sessionPtr->GetExtConnection(bundleName); + sessionConnection->DisconnectBackupExtAbility(); + } + sessionPtr->StopFwkTimer(bundleName); + sessionPtr->StopExtTimer(bundleName); + thisPtr->ClearSessionAndSchedInfo(bundleName); + thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + } catch (...) { + HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); + thisPtr->ClearSessionAndSchedInfo(bundleName); + thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + } + }; +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index 7df256035..deb63ff3c 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -413,7 +413,8 @@ ErrCode Service::AppIncrementalFileReady(const std::string &fileName, UniqueFd f // 通知extension清空缓存 proxy->HandleClear(); // 清除Timer - session_->BundleExtTimerStop(callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); // 通知TOOL 备份完成 HILOGI("reverse: Will notify IncrementalBackupOnBundleFinished"); session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(BError(BError::Codes::OK), @@ -457,7 +458,8 @@ ErrCode Service::AppIncrementalDone(ErrCode errCode) return BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } proxy->HandleClear(); - session_->BundleExtTimerStop(callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); NotifyCallerCurAppIncrementDone(errCode, callerName); backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index bd6d1be91..0fa7782c6 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -43,6 +43,10 @@ void ServiceStub::ServiceStubSupplement() opToInterfaceMap_[static_cast( IServiceInterfaceCode::SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP)] = &ServiceStub::CmdGetAppLocalListAndDoIncrementalBackup; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_START_EXT_TIMER)] = + &ServiceStub::CmdStartExtTimer; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_START_FWK_TIMER)] = + &ServiceStub::CmdStartFwkTimer; } void ServiceStub::ServiceStubSuppAppendBundles() @@ -447,6 +451,38 @@ int32_t ServiceStub::CmdUpdateSendRate(MessageParcel &data, MessageParcel &reply return BError(BError::Codes::OK); } +int32_t ServiceStub::CmdStartExtTimer(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("ServiceStub::CmdStartExtTimer Begin."); + int ret = ERR_OK; + bool isExtStart; + ret = StartExtTimer(isExtStart); + if (ret != ERR_OK) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to call UpdateTimer")); + } + if (!reply.WriteBool(isExtStart)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to write result")); + } + HILOGI("ServiceStub::CmdStartExtTimer end."); + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdStartFwkTimer(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("ServiceStub::CmdStartFwkTimer Begin."); + int ret = ERR_OK; + bool isFwkStart; + ret = StartFwkTimer(isFwkStart); + if (ret != ERR_OK) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to call UpdateTimer")); + } + if (!reply.WriteBool(isFwkStart)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to write result")); + } + HILOGI("ServiceStub::CmdStartFwkTimer end."); + return BError(BError::Codes::OK); +} + int32_t ServiceStub::CmdRelease(MessageParcel &data, MessageParcel &reply) { int res = Release(); diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index 20bb48b24..9e1fa9833 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -28,6 +28,7 @@ #include "b_json/b_json_entity_ext_manage.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" +#include "b_utils/b_time.h" #include "filemgmt_libhilog.h" #include "module_ipc/service.h" #include "module_ipc/svc_restore_deps_manager.h" @@ -683,60 +684,131 @@ uint32_t SvcSessionManager::CalAppProcessTime(const std::string &bundleName) } timeout = timeout < minTimeout ? minTimeout : timeout; resTimeoutMs = (uint32_t)(timeout * invertMillisecond % UINT_MAX); /* conver second to millisecond */ - HILOGI("Calculate App extension process run timeout=%{public}u(us), bundleName=%{public}s ", resTimeoutMs, + HILOGI("Calculate App extension process run timeout=%{public}u(ms), bundleName=%{public}s ", resTimeoutMs, bundleName.c_str()); return resTimeoutMs; } -void SvcSessionManager::BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { unique_lock lock(lock_); + HILOGI("StartFwkTimer begin bundleName %{public}s", bundleName.c_str()); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("No caller token was specified"); + return false; + } + auto it = GetBackupExtNameMap(bundleName); + if (it->second.fwkTimerStatus == true) { + HILOGE("FwkTimer is registered, unregister first."); + return false; } uint32_t timeout = CalAppProcessTime(bundleName); + it->second.fwkTimerStatus = true; + it->second.timerId = timer_.Register(callback, timeout, true); + HILOGI("StartFwkTimer end bundleName %{public}s", bundleName.c_str()); + return true; +} + +bool SvcSessionManager::StopFwkTimer(const std::string &bundleName) +{ + unique_lock lock(lock_); + HILOGI("StopFwkTimer begin bundleName %{public}s", bundleName.c_str()); + if (!impl_.clientToken) { + HILOGE("No caller token was specified"); + return false; + } auto it = GetBackupExtNameMap(bundleName); - if (it->second.timerStatus == false) { - it->second.timerStatus = true; - it->second.extTimerId = extBundleTimer.Register(callback, timeout, true); + if (it->second.fwkTimerStatus == false) { + HILOGE("FwkTimer is unregistered, register first."); + return true; } + + it->second.fwkTimerStatus = false; + timer_.Unregister(it->second.timerId); + HILOGI("StopFwkTimer end bundleName %{public}s", bundleName.c_str()); + return true; } -bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, - const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { unique_lock lock(lock_); + HILOGI("StartExtTimer begin bundleName %{public}s", bundleName.c_str()); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("No caller token was specified"); + return false; + } + auto it = GetBackupExtNameMap(bundleName); + if (it->second.extTimerStatus == true) { + HILOGE("ExtTimer is registered, unregister first."); + return false; } + uint32_t timeout = it->second.timeCount; + timeout = (timeout != 0) ? timeout : CalAppProcessTime(bundleName); + it->second.extTimerStatus = true; + it->second.startTime = static_cast(TimeUtils::GetTimeMS()); + it->second.timeCount = timeout; + it->second.timerId = timer_.Register(callback, timeout, true); + HILOGI("StartExtTimer end, timeout %{public}u(ms), bundleName %{public}s", timeout, bundleName.c_str()); + return true; +} +bool SvcSessionManager::StopExtTimer(const std::string &bundleName) +{ + unique_lock lock(lock_); + HILOGI("StopExtTimer begin bundleName %{public}s", bundleName.c_str()); + if (!impl_.clientToken) { + HILOGE("No caller token was specified"); + return false; + } auto it = GetBackupExtNameMap(bundleName); - if (it->second.timerStatus == true) { - // 定时器已存在,则先销毁,再重新注册 - it->second.timerStatus = false; - extBundleTimer.Unregister(it->second.extTimerId); - HILOGI("UpdateTimer timeout=%{public}u(ms), bundleName=%{public}s ", - timeOut, bundleName.c_str()); - it->second.extTimerId = extBundleTimer.Register(callback, timeOut, true); - it->second.timerStatus = true; + if (it->second.extTimerStatus == false) { + HILOGE("ExtTimer is unregistered, register first."); return true; } - return false; + + it->second.extTimerStatus = false; + it->second.startTime = 0; + it->second.timeCount = 0; + timer_.Unregister(it->second.timerId); + HILOGI("StopExtTimer end bundleName %{public}s", bundleName.c_str()); + return true; } -void SvcSessionManager::BundleExtTimerStop(const std::string &bundleName) +bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, + const Utils::Timer::TimerCallback &callback) { unique_lock lock(lock_); + HILOGI("UpdateTimer begin bundleName %{public}s", bundleName.c_str()); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("No caller token was specified"); + return false; } auto it = GetBackupExtNameMap(bundleName); - if (it->second.timerStatus == true) { - it->second.timerStatus = false; - extBundleTimer.Unregister(it->second.extTimerId); + if (it->second.extTimerStatus == false) { + HILOGI("ExtTimer is unregistered, just count. timeout %{public}u(ms), timeCount %{public}u(ms)", + timeOut, it->second.timeCount); + return true; } + + if (it->second.startTime == 0) { + HILOGE("ExtTimer is registered, but start time is zero."); + return false; + } + + it->second.timeCount += timeOut; + uint32_t updateTime = static_cast(TimeUtils::GetTimeMS()); + uint32_t elapseTime = updateTime - it->second.startTime; + uint32_t realTimeout = it->second.timeCount - elapseTime; + timer_.Unregister(it->second.timerId); + HILOGI("UpdateTimer timeout %{public}u(ms), timeCount %{public}u(ms), elapseTime %{public}u(ms)," + "realTimeout %{public}u(ms), bundleName %{public}s ", + timeOut, it->second.timeCount, elapseTime, realTimeout, bundleName.c_str()); + it->second.timerId = timer_.Register(callback, realTimeout, true); + it->second.extTimerStatus = true; + HILOGI("UpdateTimer end bundleName %{public}s", bundleName.c_str()); + return true; } void SvcSessionManager::IncreaseSessionCnt() @@ -768,9 +840,10 @@ void SvcSessionManager::ClearSessionData() unique_lock lock(lock_); for (auto &&it : impl_.backupExtNameMap) { // clear timer - if (it.second.timerStatus == true) { - it.second.timerStatus = false; - extBundleTimer.Unregister(it.second.extTimerId); + if (it.second.fwkTimerStatus == true || it.second.extTimerStatus == true) { + it.second.fwkTimerStatus = false; + it.second.extTimerStatus = false; + timer_.Unregister(it.second.timerId); } // disconnect extension if (it.second.schedAction == BConstants::ServiceSchedAction::RUNNING) { diff --git a/tests/mock/backup_kit_inner/service_proxy_mock.cpp b/tests/mock/backup_kit_inner/service_proxy_mock.cpp index 95af50b71..8066f1222 100644 --- a/tests/mock/backup_kit_inner/service_proxy_mock.cpp +++ b/tests/mock/backup_kit_inner/service_proxy_mock.cpp @@ -182,6 +182,15 @@ ErrCode ServiceProxy::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool return BError(BError::Codes::OK); } +ErrCode ServiceProxy::StartExtTimer(bool &isExtStart) +{ + return BError(BError::Codes::OK); +} +ErrCode ServiceProxy::StartFwkTimer(bool &isFwkStart) +{ + return BError(BError::Codes::OK); +} + ErrCode ServiceProxy::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) { return BError(BError::Codes::OK); diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index c058c5e83..a1cea2b9a 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -216,6 +216,16 @@ ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result) return BError(BError::Codes::OK); } +ErrCode Service::StartExtTimer(bool &isExtStart) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::StartFwkTimer(bool &isFwkStart) +{ + return BError(BError::Codes::OK); +} + ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) { return BError(BError::Codes::OK); diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 53b97b777..dcaf5e5ec 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -354,8 +354,24 @@ void SvcSessionManager::SetBundleDataSize(const std::string &bundleName, int64_t it->second.dataSize = dataSize; } -void SvcSessionManager::BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { + return true; +} + +bool SvcSessionManager::StopFwkTimer(const std::string &bundleName) +{ + return true; +} + +bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +{ + return true; +} + +bool SvcSessionManager::StopExtTimer(const std::string &bundleName) +{ + return true; } bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, @@ -364,8 +380,6 @@ bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t time return true; } -void SvcSessionManager::BundleExtTimerStop(const std::string &bundleName) {} - void SvcSessionManager::IncreaseSessionCnt() {} void SvcSessionManager::DecreaseSessionCnt() {} diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp index 80acd08fc..6176f43dd 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -219,20 +219,30 @@ void SvcSessionManager::SetBundleDataSize(const std::string &bundleName, int64_t BackupSvcSessionManager::session->SetBundleDataSize(bundleName, dataSize); } -void SvcSessionManager::BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { - BackupSvcSessionManager::session->BundleExtTimerStart(bundleName, callback); + return BackupSvcSessionManager::session->StartFwkTimer(bundleName, callback); } -bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, - const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StopFwkTimer(const std::string &bundleName) { - return BackupSvcSessionManager::session->UpdateTimer(bundleName, timeOut, callback); + return BackupSvcSessionManager::session->StopFwkTimer(bundleName); +} + +bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +{ + return BackupSvcSessionManager::session->StartExtTimer(bundleName, callback); } -void SvcSessionManager::BundleExtTimerStop(const std::string &bundleName) +bool SvcSessionManager::StopExtTimer(const std::string &bundleName) { - BackupSvcSessionManager::session->BundleExtTimerStop(bundleName); + return BackupSvcSessionManager::session->StopExtTimer(bundleName); +} + +bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, + const Utils::Timer::TimerCallback &callback) +{ + return BackupSvcSessionManager::session->UpdateTimer(bundleName, timeOut, callback); } void SvcSessionManager::IncreaseSessionCnt() diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.h b/tests/mock/module_ipc/svc_session_manager_throw_mock.h index f00d6e93d..a916d7c6a 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -67,9 +67,11 @@ public: virtual void SetBundleVersionName(const std::string &, std::string) = 0; virtual std::string GetBundleVersionName(const std::string &) = 0; virtual void SetBundleDataSize(const std::string &, int64_t) = 0; - virtual void BundleExtTimerStart(const std::string &, const Utils::Timer::TimerCallback &) = 0; + virtual bool StartFwkTimer(const std::string &, const Utils::Timer::TimerCallback &) = 0; + virtual bool StopFwkTimer(const std::string &) = 0; + virtual bool StartExtTimer(const std::string &, const Utils::Timer::TimerCallback &) = 0; + virtual bool StopExtTimer(const std::string &) = 0; virtual bool UpdateTimer(const std::string &, uint32_t, const Utils::Timer::TimerCallback &) = 0; - virtual void BundleExtTimerStop(const std::string &) = 0; virtual void IncreaseSessionCnt() = 0; virtual void DecreaseSessionCnt() = 0; virtual int32_t GetMemParaCurSize() = 0; @@ -130,9 +132,11 @@ public: MOCK_METHOD(void, SetBundleVersionName, (const std::string &, std::string)); MOCK_METHOD(std::string, GetBundleVersionName, (const std::string &)); MOCK_METHOD(void, SetBundleDataSize, (const std::string &, int64_t)); - MOCK_METHOD(void, BundleExtTimerStart, (const std::string &, const Utils::Timer::TimerCallback &)); + MOCK_METHOD(bool, StartFwkTimer, (const std::string &, const Utils::Timer::TimerCallback &)); + MOCK_METHOD(bool, StopFwkTimer, (const std::string &)); + MOCK_METHOD(bool, StartExtTimer, (const std::string &, const Utils::Timer::TimerCallback &)); + MOCK_METHOD(bool, StopExtTimer, (const std::string &)); MOCK_METHOD(bool, UpdateTimer, (const std::string &, uint32_t, const Utils::Timer::TimerCallback &)); - MOCK_METHOD(void, BundleExtTimerStop, (const std::string &)); MOCK_METHOD(void, IncreaseSessionCnt, ()); MOCK_METHOD(void, DecreaseSessionCnt, ()); MOCK_METHOD(int32_t, GetMemParaCurSize, ()); diff --git a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h index 0a0ffa7e8..7b6f60248 100644 --- a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h @@ -143,6 +143,16 @@ public: return BError(BError::Codes::OK); } + ErrCode StartExtTimer(bool &isExtStart) override + { + return BError(BError::Codes::OK); + } + + ErrCode StartFwkTimer(bool &isFwkStart) override + { + return BError(BError::Codes::OK); + } + ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override { return BError(BError::Codes::OK); diff --git a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp index 307c3c7e0..d241322b0 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -80,6 +80,8 @@ public: MOCK_METHOD2(GetIncrementalFileHandle, ErrCode(const std::string &bundleName, const std::string &fileName)); MOCK_METHOD2(GetBackupInfo, ErrCode(string &bundleName, string &result)); MOCK_METHOD3(UpdateTimer, ErrCode(BundleName &bundleName, uint32_t timeOut, bool &result)); + MOCK_METHOD1(StartExtTimer, ErrCode(bool &isExtStart)); + MOCK_METHOD1(StartFwkTimer, ErrCode(bool &isFwkStart)); MOCK_METHOD3(UpdateSendRate, ErrCode(std::string &bundleName, int32_t sendRate, bool &result)); }; diff --git a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp index 06dc18af3..1b83632f0 100644 --- a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp @@ -529,8 +529,9 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_OnBackupExtensionDied_0100, testing EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, BundleExtTimerStop(_)).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, StopFwkTimer(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); + return true; })); EXPECT_CALL(*sessionMock, RemoveExtInfo(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); @@ -548,40 +549,6 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_OnBackupExtensionDied_0100, testing GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_OnBackupExtensionDied_0100"; } -/** - * @tc.number: SUB_Service_throw_ExtConnectDied_0100 - * @tc.name: SUB_Service_throw_ExtConnectDied_0100 - * @tc.desc: 测试 ExtConnectDied 接口的 catch 分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: issuesIAC04T - */ -HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtConnectDied_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_ExtConnectDied_0100"; - try { - EXPECT_NE(service, nullptr); - string callName; - EXPECT_CALL(*sessionMock, BundleExtTimerStop(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, RemoveExtInfo(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return IServiceReverse::Scenario::UNDEFINED; - })); - service->ExtConnectDied(callName); - EXPECT_TRUE(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by ExtConnectDied."; - } - GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_ExtConnectDied_0100"; -} - /** * @tc.number: SUB_Service_throw_ExtStart_0100 * @tc.name: SUB_Service_throw_ExtStart_0100 @@ -687,40 +654,6 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_NoticeClientFinish_0100, testing::e GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_NoticeClientFinish_0100"; } -/** - * @tc.number: SUB_Service_throw_ExtConnectDone_0100 - * @tc.name: SUB_Service_throw_ExtConnectDone_0100 - * @tc.desc: 测试 ExtConnectDone 接口的 catch 分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: issuesIAC04T - */ -HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtConnectDone_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_ExtConnectDone_0100"; - try { - EXPECT_NE(service, nullptr); - string bundleName; - EXPECT_CALL(*sessionMock, BundleExtTimerStart(_, _)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, RemoveExtInfo(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return IServiceReverse::Scenario::UNDEFINED; - })); - service->ExtConnectDone(bundleName); - EXPECT_TRUE(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by ExtConnectDone."; - } - GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_ExtConnectDone_0100"; -} - /** * @tc.number: SUB_Service_throw_ClearSessionAndSchedInfo_0100 * @tc.name: SUB_Service_throw_ClearSessionAndSchedInfo_0100 diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp index 411ade2de..0f6bb9407 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp @@ -1704,47 +1704,47 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_SetBundleDataSize_0100, te } /** - * @tc.number: SUB_backup_sa_session_BundleExtTimerStart_0100 - * @tc.name: SUB_backup_sa_session_BundleExtTimerStart_0100 - * @tc.desc: 测试 BundleExtTimerStart + * @tc.number: SUB_backup_sa_session_StartFwkTimer_0100 + * @tc.name: SUB_backup_sa_session_StartFwkTimer_0100 + * @tc.desc: 测试 StartFwkTimer * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 * @tc.require: I6F3GV */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_BundleExtTimerStart_0100, testing::ext::TestSize.Level1) +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_StartFwkTimer_0100, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_BundleExtTimerStart_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_StartFwkTimer_0100"; try { auto callback = []() -> void {}; - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->BundleExtTimerStart(BUNDLE_NAME, callback); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + auto ret = sessionManagerPtr_->StartFwkTimer(BUNDLE_NAME, callback); + EXPECT_FALSE(ret); BackupExtInfo info; - info.timerStatus = false; + info.fwkTimerStatus = false; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStart(BUNDLE_NAME, callback); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StartFwkTimer(BUNDLE_NAME, callback); + EXPECT_TRUE(ret); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); - info.timerStatus = true; + info.fwkTimerStatus = true; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStart(BUNDLE_NAME, callback); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StartFwkTimer(BUNDLE_NAME, callback); + EXPECT_FALSE(ret); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by BundleExtTimerStart."; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by StartFwkTimer."; } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_BundleExtTimerStart_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_StartFwkTimer_0100"; } /** @@ -1761,29 +1761,35 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_UpdateTimer_0100, testing: GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_UpdateTimer_0100"; try { auto callback = []() -> void {}; - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + auto ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); + EXPECT_FALSE(ret); BackupExtInfo info; - info.timerStatus = false; + info.extTimerStatus = false; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - auto ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); - EXPECT_FALSE(ret); + ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); + EXPECT_TRUE(ret); - info.timerStatus = true; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; + ret = sessionManagerPtr_->StartExtTimer(BUNDLE_NAME, callback); + EXPECT_TRUE(ret); ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); EXPECT_TRUE(ret); + ret = sessionManagerPtr_->StopExtTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); + + info.extTimerStatus = true; + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap.clear(); + sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; + ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); + EXPECT_FALSE(ret); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by UpdateTimer."; @@ -1792,46 +1798,42 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_UpdateTimer_0100, testing: } /** - * @tc.number: SUB_backup_sa_session_BundleExtTimerStop_0100 - * @tc.name: SUB_backup_sa_session_BundleExtTimerStop_0100 - * @tc.desc: 测试 BundleExtTimerStop + * @tc.number: SUB_backup_sa_session_StopFwkTimer_0100 + * @tc.name: SUB_backup_sa_session_StopFwkTimer_0100 + * @tc.desc: 测试 StopFwkTimer * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 * @tc.require: I6F3GV */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_BundleExtTimerStop_0100, testing::ext::TestSize.Level1) +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_StopFwkTimer_0100, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_BundleExtTimerStop_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_StopFwkTimer_0100"; try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->BundleExtTimerStop(BUNDLE_NAME); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + auto ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_FALSE(ret); BackupExtInfo info; - info.timerStatus = false; + info.fwkTimerStatus = false; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStop(BUNDLE_NAME); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); - info.timerStatus = true; + info.fwkTimerStatus = true; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStop(BUNDLE_NAME); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by BundleExtTimerStop."; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by StopFwkTimer."; } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_BundleExtTimerStop_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_StopFwkTimer_0100"; } /** @@ -1848,7 +1850,7 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_ClearSessionData_0100, tes GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_ClearSessionData_0100"; try { BackupExtInfo info; - info.timerStatus = true; + info.fwkTimerStatus = true; info.schedAction = BConstants::ServiceSchedAction::RUNNING; info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); EXPECT_TRUE(sessionManagerPtr_ != nullptr); @@ -1857,7 +1859,7 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_ClearSessionData_0100, tes sessionManagerPtr_->ClearSessionData(); EXPECT_TRUE(true); - info.timerStatus = false; + info.fwkTimerStatus = false; info.schedAction = BConstants::ServiceSchedAction::WAIT; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.cpp b/tests/unittests/backup_sa/session/service_proxy_mock.cpp index 722084256..917725a54 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.cpp +++ b/tests/unittests/backup_sa/session/service_proxy_mock.cpp @@ -162,6 +162,16 @@ ErrCode ServiceProxy::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool return BError(BError::Codes::OK); } +ErrCode ServiceProxy::StartExtTimer(bool &isExtStart) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::StartFwkTimer(bool &isFwkStart) +{ + return BError(BError::Codes::OK); +} + ErrCode ServiceProxy::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) { return BError(BError::Codes::OK); diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 151ab2480..1ff282364 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -77,6 +77,7 @@ ohos_shared_library("backup_utils") { "src/b_sa/b_sa_utils.cpp", "src/b_tarball/b_tarball_cmdline.cpp", "src/b_tarball/b_tarball_factory.cpp", + "src/b_utils/b_time.cpp", ] configs = [ ":utils_private_config" ] diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index 7d85e5f90..aeb11cd77 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -77,6 +77,7 @@ constexpr int MAX_FD_SEND_RATE = 800; // 允许应用申请的最大FD数量 constexpr int MIN_FD_SEND_RATE = 0; // 允许应用申请的最小FD数量 constexpr int DEFAULT_FD_SEND_RATE = 60; // 框架默认的FD数量 constexpr int32_t PARAM_STARING_MAX_MEMORY = 2 * 1024 * 1024; +constexpr uint32_t H2MS = 60 * 60 * 1000; // backup.para内配置项的名称,该配置项值为true时可在不更新hap包的情况下,可以读取包管理元数据配置文件的内容 static inline std::string BACKUP_DEBUG_OVERRIDE_EXTENSION_CONFIG_KEY = "backup.debug.overrideExtensionConfig"; diff --git a/utils/include/b_sa/b_sa_utils.h b/utils/include/b_sa/b_sa_utils.h index 86d1b8aa9..b8d3edf4c 100644 --- a/utils/include/b_sa/b_sa_utils.h +++ b/utils/include/b_sa/b_sa_utils.h @@ -25,5 +25,5 @@ public: static bool CheckPermission(const std::string &permission); static bool IsSystemApp(); }; -} // namespace OHOS::FileManagement::Backup::BEncryption +} // namespace OHOS::FileManagement::Backup::SAUtils #endif // OHOS_FILEMGMT_BACKUP_B_SA_H \ No newline at end of file diff --git a/utils/include/b_utils/b_time.h b/utils/include/b_utils/b_time.h new file mode 100644 index 000000000..77560a7b4 --- /dev/null +++ b/utils/include/b_utils/b_time.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_TIME_H +#define OHOS_FILEMGMT_BACKUP_B_TIME_H +#include + +namespace OHOS::FileManagement::Backup { +class TimeUtils { +public: + static int64_t GetTimeS(); + static int64_t GetTimeMS(); + static int64_t GetTimeUS(); +}; +} // namespace OHOS::FileManagement::TimeUtils +#endif // OHOS_FILEMGMT_BACKUP_B_TIME_H \ No newline at end of file diff --git a/utils/src/b_utils/b_time.cpp b/utils/src/b_utils/b_time.cpp new file mode 100644 index 000000000..6656cf582 --- /dev/null +++ b/utils/src/b_utils/b_time.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_utils/b_time.h" +#include + +namespace OHOS::FileManagement::Backup { +int64_t TimeUtils::GetTimeS() +{ + std::chrono::seconds nowS = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowS.count(); +} + +int64_t TimeUtils::GetTimeMS() +{ + std::chrono::milliseconds nowMs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowMs.count(); +} + +int64_t TimeUtils::GetTimeUS() +{ + std::chrono::microseconds nowUs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowUs.count(); +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From b219ac3f2eabdef00579dc5b00210372cd0fda14 Mon Sep 17 00:00:00 2001 From: hunili Date: Sun, 18 Aug 2024 16:17:51 +0800 Subject: [PATCH 49/53] Modify untar logic issue: https://gitee.com/openharmony/filemanagement_app_file_service/issues/IAKRVA Signed-off-by: hunili --- frameworks/native/backup_ext/src/untar_file.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/frameworks/native/backup_ext/src/untar_file.cpp b/frameworks/native/backup_ext/src/untar_file.cpp index 05931009e..d04e7ebe6 100644 --- a/frameworks/native/backup_ext/src/untar_file.cpp +++ b/frameworks/native/backup_ext/src/untar_file.cpp @@ -130,7 +130,7 @@ std::tuple UntarFile::UnPacket( fclose(tarFilePtr_); tarFilePtr_ = nullptr; - return {ret, fileInfos, errInfos}; + return {0, fileInfos, errInfos}; } std::tuple UntarFile::IncrementalUnPacket( @@ -151,7 +151,7 @@ std::tuple UntarFile::IncrementalUnPacket( fclose(tarFilePtr_); tarFilePtr_ = nullptr; - return {ret, fileInfos, errFileInfos}; + return {0, fileInfos, errFileInfos}; } off_t UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStatInfo &info) @@ -225,8 +225,8 @@ bool UntarFile::CheckIfTarBlockValid(char *buff, size_t buffLen, TarHeader *head if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) { HILOGE("Parsing tar file completed, tailBuff is empty."); ret = 0; + return false; } - return false; } // check header if (!IsValidTarBlock(*header)) { @@ -284,9 +284,9 @@ int UntarFile::DealIncreParseTarFileResult(const std::tuple Date: Mon, 19 Aug 2024 11:53:30 +0800 Subject: [PATCH 50/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: I7d4a784b6a6b1b226b18747b95f4bc281997e8e6 --- .../library_func_mock/library_func_mock.cpp | 49 ++++ .../library_func_mock/library_func_mock.h | 50 ++++ .../backup_impl/service_proxy_test.cpp | 35 +++ tests/unittests/backup_ext/BUILD.gn | 76 +++++ .../backup_ext/untar_file_sup_test.cpp | 269 ++++++++++++++++++ 5 files changed, 479 insertions(+) create mode 100644 tests/mock/library_func_mock/library_func_mock.cpp create mode 100644 tests/mock/library_func_mock/library_func_mock.h create mode 100644 tests/unittests/backup_ext/untar_file_sup_test.cpp diff --git a/tests/mock/library_func_mock/library_func_mock.cpp b/tests/mock/library_func_mock/library_func_mock.cpp new file mode 100644 index 000000000..5ff83cc46 --- /dev/null +++ b/tests/mock/library_func_mock/library_func_mock.cpp @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. + */ + +#include "library_func_mock.h" + +using namespace OHOS::AppFileService; +int fseeko(FILE *stream, off_t offset, int whence) +{ + if (LibraryFunc::libraryFunc_ == nullptr) { + return -1; + } + return LibraryFunc::libraryFunc_->fseeko(stream, offset, whence); +} + +off_t ftello(FILE *stream) +{ + if (LibraryFunc::libraryFunc_ == nullptr) { + return -1; + } + return LibraryFunc::libraryFunc_->ftello(stream); +} + +int access(const char *pathname, int mode) +{ + if (LibraryFunc::libraryFunc_ == nullptr) { + return -1; + } + return LibraryFunc::libraryFunc_->access(pathname, mode); +} + +int mkdir(const char *pathname, mode_t mode) +{ + if (LibraryFunc::libraryFunc_ == nullptr) { + return -1; + } + return LibraryFunc::libraryFunc_->mkdir(pathname, mode); +} \ No newline at end of file diff --git a/tests/mock/library_func_mock/library_func_mock.h b/tests/mock/library_func_mock/library_func_mock.h new file mode 100644 index 000000000..a6cc5a1e2 --- /dev/null +++ b/tests/mock/library_func_mock/library_func_mock.h @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef FILEMANAGEMENT_APP_FILE_SERVICE_LIBRARY_FUNC_MOCK_H +#define FILEMANAGEMENT_APP_FILE_SERVICE_LIBRARY_FUNC_MOCK_H + +#include + +#include +#include +#include +#include +#include + +namespace OHOS { +namespace AppFileService { +class LibraryFunc { +public: + virtual ~LibraryFunc() = default; + virtual int fseeko(FILE *stream, off_t offset, int whence) = 0; + virtual off_t ftello(FILE *stream) = 0; + virtual int access(const char *pathname, int mode) = 0; + virtual int mkdir(const char *pathname, mode_t mode) = 0; +public: + static inline std::shared_ptr libraryFunc_ = nullptr; +}; + +class LibraryFuncMock : public LibraryFunc { +public: + MOCK_METHOD3(fseeko, int(FILE *stream, off_t offset, int whence)); + MOCK_METHOD1(ftello, off_t(FILE *stream)); + MOCK_METHOD2(access, int(const char *pathname, int mode)); + MOCK_METHOD2(mkdir, int(const char *pathname, mode_t mode)); +}; +} // namespace AppFileService +} // namespace OHOS + +#endif // FILEMANAGEMENT_APP_FILE_SERVICE_LIBRARY_FUNC_MOCK_H diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp index e27627206..1c9fd7d4d 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -742,6 +742,41 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppIncrementalFileReady_0100, testi GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppIncrementalFileReady_0100"; } +/** + * @tc.number: SUB_Service_proxy_AppIncrementalFileReady_0200 + * @tc.name: SUB_Service_proxy_AppIncrementalFileReady_0200 + * @tc.desc: 测试 AppIncrementalFileReady 接口成功和失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I90ZV5 + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppIncrementalFileReady_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_AppIncrementalFileReady_0200"; + if (proxy_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_Service_proxy_AppIncrementalFileReady_0200 proxy_ == nullptr"; + return; + } + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Return(0)) + .WillOnce(Return(0)); + + string bundleName = "com.example.app2backup"; + TestManager tm("AppIncrementalFileReady_0200"); + std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); + UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); + UniqueFd manifestFd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); + + int32_t result = proxy_->AppIncrementalFileReady(bundleName, UniqueFd(-1), move(manifestFd), 0); + EXPECT_EQ(result, BError(BError::Codes::OK)); + + result = proxy_->AppIncrementalFileReady(bundleName, move(fd), UniqueFd(-1), 0); + EXPECT_EQ(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppIncrementalFileReady_0200"; +} + /** * @tc.number: SUB_Service_proxy_AppIncrementalDone_0100 * @tc.name: SUB_Service_proxy_AppIncrementalDone_0100 diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index 32e37d292..1db3bd636 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -193,6 +193,81 @@ ohos_unittest("tar_file_test") { use_exceptions = true } +ohos_unittest("untar_file_sup_test") { + branch_protector_ret = "pac_ret" + sanitize = { + integer_overflow = true + cfi = true + cfi_cross_dso = true + debug = false + } + + module_out_path = path_module_out_tests + + sources = [ + "${path_backup}/frameworks/native/backup_ext/src/ext_backup.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_context_js.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_js.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp", + "${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp", + "${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp", + "${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp", + "${path_backup}/tests/mock/library_func_mock/library_func_mock.cpp", + "untar_file_sup_test.cpp", + ] + sources += backup_mock_proxy_src + + include_dirs = [ + "${path_ability_runtime}/services/common/include", + "${path_ability_runtime}/interfaces/kits/napi/aafwk/inner/napi_common", + "${path_ability_runtime}/interfaces/kits/native/appkit/ability_runtime", + "${path_backup}/frameworks/native/backup_ext/include", + "${path_backup}/frameworks/native/backup_ext/src", + "${path_backup}/interfaces/inner_api/native/backup_kit_inner/", + "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", + "${path_backup}/frameworks/native/backup_kit_inner/include", + "${path_backup}/tests/mock/library_func_mock", + "${path_backup}/utils/include", + "${path_napi}/native_engine", + ] + include_dirs += backup_mock_utils_include + + deps = [ + "${path_backup}/interfaces/inner_api/native/backup_kit_inner:backup_kit_inner", + "${path_backup}/interfaces/innerkits/native:sandbox_helper_native", + "${path_backup}/tests/utils:backup_test_utils", + "${path_backup}/utils:backup_utils", + "${path_googletest}:gmock_main", + "${path_jsoncpp}:jsoncpp", + ] + + cflags = [ "--coverage" ] + ldflags = [ "--coverage" ] + cflags_cc = [ "--coverage" ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:abilitykit_native", + "ability_runtime:app_context", + "ability_runtime:appkit_native", + "ability_runtime:runtime", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "samgr:samgr_proxy", + ] + + defines = [ "private=public" ] + + use_exceptions = true +} + ohos_unittest("untar_file_test") { branch_protector_ret = "pac_ret" sanitize = { @@ -333,6 +408,7 @@ group("backup_ext_test") { ":ext_extension_stub_test", ":ext_extension_test", ":tar_file_test", + ":untar_file_sup_test", ":untar_file_test", ] } diff --git a/tests/unittests/backup_ext/untar_file_sup_test.cpp b/tests/unittests/backup_ext/untar_file_sup_test.cpp new file mode 100644 index 000000000..7f3ad3471 --- /dev/null +++ b/tests/unittests/backup_ext/untar_file_sup_test.cpp @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "b_error/b_error.h" +#include "file_ex.h" +#include "library_func_mock.h" +#include "test_manager.h" +#include "untar_file.cpp" + + +namespace OHOS::FileManagement::Backup { +using namespace std; +using namespace testing; +using namespace OHOS::AppFileService; +class UntarFileSupTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(); + void SetUp() override {}; + void TearDown() override {}; + static inline shared_ptr funcMock = nullptr; +}; + +static void ClearCache() +{ + UntarFile::GetInstance().rootPath_.clear(); + UntarFile::GetInstance().tarFileSize_ = 0; + UntarFile::GetInstance().tarFileBlockCnt_ = 0; + UntarFile::GetInstance().pos_ = 0; + UntarFile::GetInstance().readCnt_ = 0; + if (UntarFile::GetInstance().tarFilePtr_ != nullptr) { + fclose(UntarFile::GetInstance().tarFilePtr_); + UntarFile::GetInstance().tarFilePtr_ = nullptr; + } + TarFile::GetInstance().fileCount_ = 0; + TarFile::GetInstance().tarMap_.clear(); + TarFile::GetInstance().rootPath_.clear(); + TarFile::GetInstance().packagePath_.clear(); + TarFile::GetInstance().baseTarName_.clear(); + TarFile::GetInstance().tarFileName_.clear(); + TarFile::GetInstance().ioBuffer_.clear(); + TarFile::GetInstance().currentTarName_.clear(); + TarFile::GetInstance().currentTarFileSize_ = 0; + TarFile::GetInstance().tarFileCount_ = 0; + TarFile::GetInstance().currentFileName_.clear(); + if (TarFile::GetInstance().currentTarFile_ != nullptr) { + fclose(TarFile::GetInstance().currentTarFile_); + TarFile::GetInstance().currentTarFile_ = nullptr; + } +} + +void UntarFileSupTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase enter"; + funcMock = make_shared(); + LibraryFuncMock::libraryFunc_ = funcMock; +} + +void UntarFileSupTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "TearDownTestCase enter"; + LibraryFuncMock::libraryFunc_ = nullptr; + funcMock = nullptr; + ClearCache(); +} + +/** + * @tc.number: SUB_Untar_File_IsEmptyBlock_0100 + * @tc.name: SUB_Untar_File_IsEmptyBlock_0100 + * @tc.desc: 测试 IsEmptyBlock + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(UntarFileSupTest, SUB_Untar_File_IsEmptyBlock_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UntarFileSupTest-begin SUB_Untar_File_IsEmptyBlock_0100"; + try { + EXPECT_EQ(IsEmptyBlock(nullptr), true); + char buff[BLOCK_SIZE] = {0}; + EXPECT_EQ(IsEmptyBlock(buff), true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UntarFileSupTest-an exception occurred by IsEmptyBlock."; + } + GTEST_LOG_(INFO) << "UntarFileSupTest-end SUB_Untar_File_IsEmptyBlock_0100"; +} + +/** + * @tc.number: SUB_Untar_File_ParseOctalStr_0100 + * @tc.name: SUB_Untar_File_ParseOctalStr_0100 + * @tc.desc: 测试 ParseOctalStr 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(UntarFileSupTest, SUB_Untar_File_ParseOctalStr_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UntarFileSupTest-begin SUB_Untar_File_ParseOctalStr_0100"; + EXPECT_EQ(ParseOctalStr("0", 0), 0); + EXPECT_EQ(ParseOctalStr("1234", 0), 0); + EXPECT_EQ(ParseOctalStr("()-891234", 10), 668); + GTEST_LOG_(INFO) << "UntarFileSupTest-end SUB_Untar_File_ParseOctalStr_0100"; +} + +/** + * @tc.number: SUB_Untar_File_GenRealPath_0100 + * @tc.name: SUB_Untar_File_GenRealPath_0100 + * @tc.desc: 测试 GenRealPath 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(UntarFileSupTest, SUB_Untar_File_GenRealPath_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UntarFileSupTest-begin SUB_Untar_File_GenRealPath_0100"; + string rootPath = ""; + string realName = ""; + EXPECT_EQ(UntarFile::GetInstance().GenRealPath(rootPath, realName), ""); + + rootPath = "rootPath"; + EXPECT_EQ(UntarFile::GetInstance().GenRealPath(rootPath, realName), ""); + + realName = "realName"; + EXPECT_EQ(UntarFile::GetInstance().GenRealPath(rootPath, realName), "rootPath/realName"); + + rootPath = "/rootPath/"; + realName = "/realName"; + EXPECT_EQ(UntarFile::GetInstance().GenRealPath(rootPath, realName), "rootPath/realName"); + GTEST_LOG_(INFO) << "UntarFileSupTest-end SUB_Untar_File_GenRealPath_0100"; +} + +/** + * @tc.number: SUB_Untar_File_ForceCreateDirectoryWithMode_0100 + * @tc.name: SUB_Untar_File_ForceCreateDirectoryWithMode_0100 + * @tc.desc: 测试 ForceCreateDirectoryWithMode 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(UntarFileSupTest, SUB_Untar_File_ForceCreateDirectoryWithMode_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UntarFileSupTest-begin SUB_Untar_File_ForceCreateDirectoryWithMode_0100"; + string rootPath = "rootPath/realName"; + EXPECT_CALL(*funcMock, access(_, _)).WillOnce(Return(1)); + EXPECT_CALL(*funcMock, mkdir(_, _)).WillOnce(Return(1)); + EXPECT_EQ(ForceCreateDirectoryWithMode(rootPath, S_IRWXU), false); + + EXPECT_CALL(*funcMock, access(_, _)).WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(0)); + EXPECT_CALL(*funcMock, mkdir(_, _)).WillOnce(Return(0)); + EXPECT_EQ(ForceCreateDirectoryWithMode(rootPath, S_IRWXU), true); + + EXPECT_CALL(*funcMock, access(_, _)).WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(1)); + EXPECT_CALL(*funcMock, mkdir(_, _)).WillOnce(Return(0)); + EXPECT_EQ(ForceCreateDirectoryWithMode(rootPath, S_IRWXU), false); + GTEST_LOG_(INFO) << "UntarFileSupTest-end SUB_Untar_File_ParseOctalStr_0100"; +} + +/** + * @tc.number: SUB_Untar_File_CreateDir_0100 + * @tc.name: SUB_Untar_File_CreateDir_0100 + * @tc.desc: 测试 CreateDir 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(UntarFileSupTest, SUB_Untar_File_CreateDir_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UntarFileSupTest-begin SUB_Untar_File_CreateDir_0100"; + string rootPath = ""; + try { + UntarFile::GetInstance().CreateDir(rootPath, S_IRWXU); + rootPath = "rootPath/realName"; + EXPECT_CALL(*funcMock, access(_, _)).WillOnce(Return(0)); + UntarFile::GetInstance().CreateDir(rootPath, S_IRWXU); + + rootPath = "rootPath/realName"; + EXPECT_CALL(*funcMock, access(_, _)).WillOnce(Return(1)).WillOnce(Return(0)) + .WillOnce(Return(1)).WillOnce(Return(0)); + EXPECT_CALL(*funcMock, mkdir(_, _)).WillOnce(Return(0)); + UntarFile::GetInstance().CreateDir(rootPath, S_IRWXU); + + EXPECT_CALL(*funcMock, access(_, _)).WillOnce(Return(1)).WillOnce(Return(0)) + .WillOnce(Return(1)).WillOnce(Return(1)); + EXPECT_CALL(*funcMock, mkdir(_, _)).WillOnce(Return(0)); + UntarFile::GetInstance().CreateDir(rootPath, S_IRWXU); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UntarFileSupTest-an exception occurred by CreateDir."; + } + GTEST_LOG_(INFO) << "UntarFileSupTest-end SUB_Untar_File_CreateDir_0100"; +} + +/** + * @tc.number: SUB_Untar_File_ParseFileByTypeFlag_0100 + * @tc.name: SUB_Untar_File_ParseFileByTypeFlag_0100 + * @tc.desc: 测试 ParseFileByTypeFlag 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(UntarFileSupTest, SUB_Untar_File_ParseFileByTypeFlag_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UntarFileSupTest-begin SUB_Untar_File_CreateDir_0100"; + FileStatInfo info; + info.fullPath = "realName"; + UntarFile::GetInstance().rootPath_ = "rootPath"; + try { + UntarFile::GetInstance().ParseFileByTypeFlag(SYMTYPE, info); + + EXPECT_CALL(*funcMock, access(_, _)).WillOnce(Return(1)).WillOnce(Return(0)) + .WillOnce(Return(1)).WillOnce(Return(0)); + EXPECT_CALL(*funcMock, mkdir(_, _)).WillOnce(Return(0)); + UntarFile::GetInstance().ParseFileByTypeFlag(DIRTYPE, info); + EXPECT_EQ(info.fullPath, "rootPath/realName"); + + EXPECT_CALL(*funcMock, fseeko(_, _, _)).WillOnce(Return(0)); + UntarFile::GetInstance().ParseFileByTypeFlag('6', info); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UntarFileSupTest-an exception occurred by ParseFileByTypeFlag."; + } + GTEST_LOG_(INFO) << "UntarFileSupTest-end SUB_Untar_File_CreateDir_0100"; +} + +/** + * @tc.number: SUB_Untar_File_IsValidTarBlock_0100 + * @tc.name: SUB_Untar_File_IsValidTarBlock_0100 + * @tc.desc: 测试 IsValidTarBlock 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(UntarFileSupTest, SUB_Untar_File_IsValidTarBlock_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UntarFileSupTest-begin SUB_Untar_File_IsValidTarBlock_0100"; + TarHeader header { .magic = "test" }; + try { + EXPECT_EQ(UntarFile::GetInstance().IsValidTarBlock(header), false); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UntarFileSupTest-an exception occurred by IsValidTarBlock."; + } + GTEST_LOG_(INFO) << "UntarFileSupTest-end SUB_Untar_File_IsValidTarBlock_0100"; +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From a25fad2371bf8fcb3f5c748525d67faa1f4ff749 Mon Sep 17 00:00:00 2001 From: lvyuanyuan Date: Mon, 19 Aug 2024 13:49:41 +0800 Subject: [PATCH 51/53] add afs testcase Signed-off-by: lvyuanyuan Change-Id: I15c9e674ab71f94b5c66bd5486debe738888349d --- tests/unittests/backup_ext/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index 1db3bd636..849943f24 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -200,6 +200,7 @@ ohos_unittest("untar_file_sup_test") { cfi = true cfi_cross_dso = true debug = false + blocklist = "${path_backup}/cfi_blocklist.txt" } module_out_path = path_module_out_tests -- Gitee From 628e9f4c54e9e32a1b7512c2cb67a5c088e4574c Mon Sep 17 00:00:00 2001 From: y30045862 Date: Sat, 17 Aug 2024 21:15:13 +0800 Subject: [PATCH 52/53] optimize move performance for filemanage and medialibrary restore Signed-off-by: yangjingbo10 Change-Id: I11a020d2ffd3d0c1e2f4a09d589478d5110afc80 --- .../native/backup_ext/include/ext_extension.h | 4 +- .../native/backup_ext/src/ext_backup.cpp | 5 +- .../backup_ext/src/ext_backup_context.cpp | 12 +- .../native/backup_ext/src/ext_extension.cpp | 112 ++++++++++++------ .../backupext_fuzzer/backupext_fuzzer.cpp | 2 +- utils/include/b_filesystem/b_file.h | 10 ++ utils/include/b_resources/b_constants.h | 14 +++ utils/src/b_filesystem/b_file.cpp | 8 ++ 8 files changed, 126 insertions(+), 41 deletions(-) diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index f74b25bb0..5b8723c19 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -58,8 +58,10 @@ public: void AsyncTaskIncrementalRestoreForUpgrade(void); public: - explicit BackupExtExtension(const std::shared_ptr &extension) : extension_(extension) + explicit BackupExtExtension(const std::shared_ptr &extension, + const std::string &bundleName) : extension_(extension) { + bundleName_ = bundleName; threadPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); } ~BackupExtExtension() diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index 1a4bc1f78..cae8e3e91 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -188,7 +188,8 @@ sptr ExtBackup::OnConnect(const AAFwk::Want &want) Extension::OnConnect(want); auto remoteObject = - sptr(new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); + sptr(new BackupExtExtension(std::static_pointer_cast(shared_from_this()), + want.GetBundle())); return remoteObject->AsObject(); } catch (const BError &e) { return nullptr; @@ -207,7 +208,7 @@ void ExtBackup::OnDisconnect(const AAFwk::Want &want) HILOGI("begin disconnect"); if (isClearData_) { auto remoteObject = sptr( - new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); + new BackupExtExtension(std::static_pointer_cast(shared_from_this()), want.GetBundle())); remoteObject->ExtClear(); } Extension::OnDisconnect(want); diff --git a/frameworks/native/backup_ext/src/ext_backup_context.cpp b/frameworks/native/backup_ext/src/ext_backup_context.cpp index 87a8a03dd..3df12d334 100644 --- a/frameworks/native/backup_ext/src/ext_backup_context.cpp +++ b/frameworks/native/backup_ext/src/ext_backup_context.cpp @@ -15,6 +15,7 @@ #include "ext_backup_context.h" +#include "b_filesystem/b_file.h" #include "b_resources/b_constants.h" namespace OHOS::FileManagement::Backup { @@ -24,7 +25,16 @@ const std::string ExtBackupContext::GetBackupDir() if (area > 1) { // 1 : el2 area return ""; } - return std::string(BConstants::BACKUP_DIR_PRE) + std::string(BConstants::CONTEXT_ELS[area]) + + + std::string path = std::string(BConstants::BACKUP_DIR_PRE) + std::string(BConstants::CONTEXT_ELS[area]) + std::string(BConstants::BACKUP_DIR_END); + std::string bundleName = GetBundleName(); + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + path = std::string(BConstants::PATH_FILEMANAGE_BACKUP_HOME) + BConstants::FILE_SEPARATOR_CHAR; + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + path = std::string(BConstants::PATH_MEDIALDATA_BACKUP_HOME) + BConstants::FILE_SEPARATOR_CHAR; + } + + return path; } } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 3ab7acc64..c1a6ea730 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -57,7 +57,6 @@ #include "b_anony/b_anony.h" namespace OHOS::FileManagement::Backup { -const string DEFAULT_TAR_PKG = "1.tar"; const string INDEX_FILE_BACKUP = string(BConstants::PATH_BUNDLE_BACKUP_HOME). append(BConstants::SA_BUNDLE_BACKUP_BACKUP). append(BConstants::EXT_BACKUP_MANAGE); @@ -68,17 +67,39 @@ const string INDEX_FILE_INCREMENTAL_BACKUP = string(BConstants::PATH_BUNDLE_BACK append(BConstants::SA_BUNDLE_BACKUP_BACKUP); using namespace std; -namespace { -const int64_t DEFAULT_SLICE_SIZE = 100 * 1024 * 1024; // 分片文件大小为100M -const uint32_t MAX_FILE_COUNT = 6000; // 单个tar包最多包含6000个文件 -const int FILE_AND_MANIFEST_FD_COUNT = 2; // 每组文件和简报数量统计 +static string GetIndexFileRestorePath(const string &bundleName) +{ + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + return string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE). + append(BConstants::EXT_BACKUP_MANAGE); + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + return string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE). + append(BConstants::EXT_BACKUP_MANAGE); + } + return INDEX_FILE_RESTORE; +} + +static string GetRestoreTempPath(const string &bundleName) +{ + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + if (mkdir(string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).data(), S_IRWXU) && errno != EEXIST) { + string str = string("Failed to create .backup folder. ").append(std::generic_category().message(errno)); + throw BError(BError::Codes::EXT_INVAL_ARG, str); + } + path = string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + path = string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } + return path; } -static std::set GetIdxFileData() +static std::set GetIdxFileData(const string &bundleName) { - UniqueFd idxFd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName); + UniqueFd idxFd(open(indexFileRestorePath.data(), O_RDONLY)); if (idxFd < 0) { - HILOGE("Failed to open idxFile = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open idxFile = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return std::set(); } BJsonCachedEntity cachedEntity(std::move(idxFd)); @@ -88,7 +109,8 @@ static std::set GetIdxFileData() std::vector BackupExtExtension::GetExtManageInfo() { - string filePath = BExcepUltils::Canonicalize(INDEX_FILE_RESTORE); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName_); + string filePath = BExcepUltils::Canonicalize(indexFileRestorePath); UniqueFd idxFd(open(filePath.data(), O_RDONLY)); if (idxFd < 0) { HILOGE("Failed to open cano_idxFile = %{private}s, err = %{public}d", filePath.c_str(), errno); @@ -181,7 +203,7 @@ UniqueFd BackupExtExtension::GetFileHandle(const string &fileName, int32_t &errC return fd; } - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string path = GetRestoreTempPath(bundleName_); if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); throw BError(BError::Codes::EXT_INVAL_ARG, str); @@ -245,9 +267,18 @@ static ErrCode GetIncreFileHandleForSpecialVersion(const string &fileName) return ERR_OK; } -static string GetIncrementalFileHandlePath(const string &fileName) +static string GetIncrementalFileHandlePath(const string &fileName, const string &bundleName) { string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + if (mkdir(string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).data(), S_IRWXU) && errno != EEXIST) { + string str = string("Failed to create .backup folder. ").append(std::generic_category().message(errno)); + throw BError(BError::Codes::EXT_INVAL_ARG, str); + } + path = string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + path = string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); throw BError(BError::Codes::EXT_INVAL_ARG, str); @@ -271,7 +302,7 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) return GetIncreFileHandleForSpecialVersion(fileName); } HILOGI("extension: GetIncrementalFileHandle single to single Name:%{public}s", GetAnonyPath(fileName).c_str()); - string tarName = GetIncrementalFileHandlePath(fileName); + string tarName = GetIncrementalFileHandlePath(fileName, bundleName_); int32_t errCode = ERR_OK; if (access(tarName.c_str(), F_OK) == 0) { HILOGE("The file already exists, tarname = %{private}s, err =%{public}d", tarName.c_str(), errno); @@ -406,7 +437,7 @@ ErrCode BackupExtExtension::PublishFile(const std::string &fileName) VerifyCaller(); // 异步执行解压操作 if (extension_->AllowToBackupRestore()) { - AsyncTaskRestore(GetIdxFileData(), GetExtManageInfo()); + AsyncTaskRestore(GetIdxFileData(bundleName_), GetExtManageInfo()); } HILOGI("End publish file"); return ERR_OK; @@ -562,7 +593,7 @@ static ErrCode TarFileReady(const TarMap &tarFileInfo, sptr proxy) if (SUCCEEDED(ret)) { HILOGI("TarFileReady: AppFileReady success for %{public}s", tarName.c_str()); // 删除文件 - RemoveFile(tarName); + RemoveFile(tarPath); } else { HILOGE("TarFileReady AppFileReady fail to be invoked for %{public}s: ret = %{public}d", tarName.c_str(), ret); } @@ -583,7 +614,7 @@ void BackupExtExtension::DoPacket(const map &srcFiles, TarMap &t totalSize += small.second; fileCount += 1; packFiles.emplace_back(small.first); - if (totalSize >= DEFAULT_SLICE_SIZE || fileCount >= MAX_FILE_COUNT) { + if (totalSize >= BConstants::DEFAULT_SLICE_SIZE || fileCount >= BConstants::MAX_FILE_COUNT) { TarMap tarMap {}; TarFile::GetInstance().Packet(packFiles, "part", path, tarMap); tar.insert(tarMap.begin(), tarMap.end()); @@ -593,7 +624,7 @@ void BackupExtExtension::DoPacket(const map &srcFiles, TarMap &t totalSize = 0; fileCount = 0; packFiles.clear(); - fdNum += FILE_AND_MANIFEST_FD_COUNT; + fdNum += BConstants::FILE_AND_MANIFEST_FD_COUNT; RefreshTimeInfo(startTime, fdNum); } } @@ -678,7 +709,7 @@ int BackupExtExtension::DoRestore(const string &fileName, const off_t fileSize) } // REM: 给定version // REM: 解压启动Extension时即挂载好的备份目录中的数据 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string path = GetRestoreTempPath(bundleName_); string tarName = path + fileName; // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore @@ -746,7 +777,7 @@ int BackupExtExtension::DoIncrementalRestore() HILOGE("Failed to do incremental restore, extension is nullptr"); throw BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr"); } - auto fileSet = GetIdxFileData(); + auto fileSet = GetIdxFileData(bundleName_); auto extManageInfo = GetExtManageInfo(); std::tuple unPacketRes; ErrCode err = ERR_OK; @@ -758,7 +789,7 @@ int BackupExtExtension::DoIncrementalRestore() } // REM: 给定version // REM: 解压启动Extension时即挂载好的备份目录中的数据 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string path = GetRestoreTempPath(bundleName_); string tarName = path + item; // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore @@ -955,10 +986,12 @@ void BackupExtExtension::RestoreBigFiles(bool appendTargetPath) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 获取索引文件内容 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + string path = GetRestoreTempPath(bundleName_); + + string indexFileRestorePath = GetIndexFileRestorePath(bundleName_); + UniqueFd fd(open(indexFileRestorePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open index json file = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return; } BJsonCachedEntity cachedEntity(move(fd)); @@ -1028,16 +1061,17 @@ void BackupExtExtension::DeleteBackupTars() return; } HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName_); + UniqueFd fd(open(indexFileRestorePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open index json file = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return; } // The directory include tars and manage.json which would be deleted BJsonCachedEntity cachedEntity(move(fd)); auto cache = cachedEntity.Structuralize(); auto info = cache.GetExtManage(); - auto path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + auto path = GetRestoreTempPath(bundleName_); auto extManageInfo = GetExtManageInfo(); for (auto &item : info) { off_t tarFileSize = 0; @@ -1049,8 +1083,8 @@ void BackupExtExtension::DeleteBackupTars() HILOGE("Failed to delete the backup tar %{public}s", tarPath.c_str()); } } - if (!RemoveFile(INDEX_FILE_RESTORE)) { - HILOGE("Failed to delete the backup index %{public}s", INDEX_FILE_RESTORE.c_str()); + if (!RemoveFile(indexFileRestorePath)) { + HILOGE("Failed to delete the backup index %{public}s", indexFileRestorePath.c_str()); } HILOGI("End execute DeleteBackupTars"); } @@ -1061,16 +1095,17 @@ void BackupExtExtension::DeleteBackupIncrementalTars() HILOGI("configured not clear data."); return; } - UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName_); + UniqueFd fd(open(indexFileRestorePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open index json file = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return; } // The directory include tars and manage.json which would be deleted BJsonCachedEntity cachedEntity(move(fd)); auto cache = cachedEntity.Structuralize(); auto info = cache.GetExtManage(); - auto path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + auto path = GetRestoreTempPath(bundleName_); auto extManageInfo = GetExtManageInfo(); for (auto &item : info) { off_t tarFileSize = 0; @@ -1087,10 +1122,10 @@ void BackupExtExtension::DeleteBackupIncrementalTars() HILOGE("Failed to delete the backup report %{private}s, err = %{public}d", reportPath.c_str(), errno); } } - if (!RemoveFile(INDEX_FILE_RESTORE)) { - HILOGE("Failed to delete the backup index %{public}s", INDEX_FILE_RESTORE.c_str()); + if (!RemoveFile(indexFileRestorePath)) { + HILOGE("Failed to delete the backup index %{public}s", indexFileRestorePath.c_str()); } - string reportManagePath = GetReportFileName(INDEX_FILE_RESTORE); // GetIncrementalFileHandle创建的空fd + string reportManagePath = GetReportFileName(indexFileRestorePath); // GetIncrementalFileHandle创建的空fd if (!RemoveFile(reportManagePath)) { HILOGE("Failed to delete the backup report index %{public}s", reportManagePath.c_str()); } @@ -1380,6 +1415,7 @@ void BackupExtExtension::DoClear() } string backupCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); string restoreCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string specialRestoreCache = GetRestoreTempPath(bundleName_); if (!ForceRemoveDirectory(backupCache)) { HILOGI("Failed to delete the backup cache %{public}s", backupCache.c_str()); @@ -1388,6 +1424,10 @@ void BackupExtExtension::DoClear() if (!ForceRemoveDirectory(restoreCache)) { HILOGI("Failed to delete the restore cache %{public}s", restoreCache.c_str()); } + + if (!ForceRemoveDirectory(specialRestoreCache)) { + HILOGI("Failed to delete cache for filemanager or medialibrary %{public}s", specialRestoreCache.c_str()); + } // delete el1 backup/restore ForceRemoveDirectory( string(BConstants::PATH_BUNDLE_BACKUP_HOME_EL1).append(BConstants::SA_BUNDLE_BACKUP_BACKUP)); @@ -1764,7 +1804,7 @@ ErrCode BackupExtExtension::IncrementalBigFileReady(const TarMap &pkgInfo, } else { HILOGE("IncrementalBigFileReady interface fails to be invoked: %{public}d", ret); } - fdNum += FILE_AND_MANIFEST_FD_COUNT; + fdNum += BConstants::FILE_AND_MANIFEST_FD_COUNT; RefreshTimeInfo(startTime, fdNum); } HILOGI("IncrementalBigFileReady End"); @@ -1886,7 +1926,7 @@ void BackupExtExtension::IncrementalPacket(const vector & fileCount += 1; packFiles.emplace_back(small.filePath); tarInfos.emplace_back(small); - if (totalSize >= DEFAULT_SLICE_SIZE || fileCount >= MAX_FILE_COUNT) { + if (totalSize >= BConstants::DEFAULT_SLICE_SIZE || fileCount >= BConstants::MAX_FILE_COUNT) { TarMap tarMap {}; TarFile::GetInstance().Packet(packFiles, partName, path, tarMap); tar.insert(tarMap.begin(), tarMap.end()); @@ -1897,7 +1937,7 @@ void BackupExtExtension::IncrementalPacket(const vector & fileCount = 0; packFiles.clear(); tarInfos.clear(); - fdNum += FILE_AND_MANIFEST_FD_COUNT; + fdNum += BConstants::FILE_AND_MANIFEST_FD_COUNT; RefreshTimeInfo(startTime, fdNum); } } diff --git a/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp b/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp index 2528f0082..d00abd06b 100644 --- a/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp +++ b/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp @@ -273,7 +273,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ auto extBackup = std::make_shared(); - auto extension = std::make_shared(extBackup); + auto extension = std::make_shared(extBackup, ""); OHOS::OnRemoteRequestFuzzTest(extension, data, size); OHOS::InitFuzzTest(extBackup, data, size); diff --git a/utils/include/b_filesystem/b_file.h b/utils/include/b_filesystem/b_file.h index 2d69e75fd..c2cc3c8af 100644 --- a/utils/include/b_filesystem/b_file.h +++ b/utils/include/b_filesystem/b_file.h @@ -82,6 +82,16 @@ public: * @return false some error occur */ static bool GetRealPath(const string &path, string &realPath); + + /** + * @brief check if string is endswith suffix + * + * @param str str + * @param suffix suffix str + * @return true str is endswith suffix + * @return false str is not endswith suffix + */ + static bool EndsWith(const string &str, const string &suffix); private: }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index 7d85e5f90..6ca0b5e2a 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -68,6 +68,11 @@ constexpr int IPC_MAX_WAIT_TIME = 3000; // IPC通讯最大等待时间(s) constexpr int MAX_PARCELABLE_VECTOR_NUM = 10000; constexpr char FILE_SEPARATOR_CHAR = '/'; +// 分片打包常量 +const int64_t DEFAULT_SLICE_SIZE = 100 * 1024 * 1024; // 分片文件大小为100M +const uint32_t MAX_FILE_COUNT = 6000; // 单个tar包最多包含6000个文件 +const int FILE_AND_MANIFEST_FD_COUNT = 2; // 每组文件和简报数量统计 + constexpr int DEFAULT_VFS_CACHE_PRESSURE = 100; // 默认内存回收参数 constexpr int BACKUP_VFS_CACHE_PRESSURE = 10000; // 备份过程修改参数 @@ -106,6 +111,8 @@ static inline std::string_view SA_BUNDLE_BACKUP_TMP_DIR = "/tmp/"; static inline std::string_view BACKUP_TOOL_RECEIVE_DIR = "/data/backup/received/"; static inline std::string_view PATH_BUNDLE_BACKUP_HOME_EL1 = "/data/storage/el1/base/.backup"; static inline std::string_view PATH_BUNDLE_BACKUP_HOME = "/data/storage/el2/base/.backup"; +static inline std::string_view PATH_FILEMANAGE_BACKUP_HOME = "/storage/Users/currentUser/.backup"; +static inline std::string_view PATH_MEDIALDATA_BACKUP_HOME = "/storage/media/local/files/.backup"; static inline std::string_view BACKUP_TOOL_LINK_DIR = "/data/backup"; static inline std::string_view BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR = "/data/backup/incrementalreceived/"; static inline std::string_view BACKUP_TOOL_MANIFEST = "/manifest"; @@ -113,6 +120,13 @@ static inline std::string_view BACKUP_TOOL_INCREMENTAL = "/incremental"; static inline std::string BACKUP_DIR_PRE = "/data/storage/"; static inline std::string CONTEXT_ELS[] = {"el1", "el2"}; static inline std::string BACKUP_DIR_END = "/base/.backup/"; + +// 文管bundleName +static inline std::string BUNDLE_FILE_MANAGER = "hmos.filemanager"; +// 文管bundleNameSize +constexpr size_t FM_LEN = 27; +// 媒体库数据bundleName +static inline std::string BUNDLE_MEDIAL_DATA = "com.ohos.medialibrary.medialibrarydata"; // SA Ext constexpr int BACKUP_DEFAULT_SA_ID = -1; constexpr int BACKUP_SA_RELOAD_MAX = 2; diff --git a/utils/src/b_filesystem/b_file.cpp b/utils/src/b_filesystem/b_file.cpp index 097125673..27b910078 100644 --- a/utils/src/b_filesystem/b_file.cpp +++ b/utils/src/b_filesystem/b_file.cpp @@ -210,4 +210,12 @@ bool BFile::MoveFile(const string &from, const string &to) } return false; } + +bool BFile::EndsWith(const string &str, const string &suffix) +{ + if (suffix.length() > str.length()) { + return false; + } + return (str.rfind(suffix) == (str.length() - suffix.length())); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee From abe754a4bcf34b50e23527dbe87c0e2373c90999 Mon Sep 17 00:00:00 2001 From: "yaoruozi1@huawei.com" Date: Tue, 20 Aug 2024 01:05:17 +0800 Subject: [PATCH 53/53] =?UTF-8?q?=E4=BF=AE=E6=94=B9onProcessTimeout?= =?UTF-8?q?=E7=9A=84=E4=BD=BF=E7=94=A8=E6=97=B6=E6=9C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yaoruozi1@huawei.com --- .../native/backup_ext/include/ext_extension.h | 1 + .../backup_ext/src/sub_ext_extension.cpp | 18 ++++++++++++------ .../src/b_session_restore_async.cpp | 3 ++- .../b_session_restore_async_mock.cpp | 2 ++ 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index 40ef8944a..b40efcbdf 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -65,6 +65,7 @@ public: } ~BackupExtExtension() { + onProcessTimeoutTimer_.Shutdown(); threadPool_.Stop(); } diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index ae77b3e75..fb0cf64c7 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -473,8 +473,8 @@ void BackupExtExtension::StartOnProcessTaskThread(wptr obj, { HILOGI("Begin Create onProcess Task Thread"); onProcessTimeoutTimer_.Setup(); - SyncCallJsOnProcessTask(obj, scenario); StartOnProcessTimeOutTimer(obj); + SyncCallJsOnProcessTask(obj, scenario); callJsOnProcessThread_ = std::thread([obj, scenario]() { auto extPtr = obj.promote(); if (extPtr == nullptr) { @@ -489,8 +489,6 @@ void BackupExtExtension::StartOnProcessTaskThread(wptr obj, void BackupExtExtension::ExecCallOnProcessTask(wptr obj, BackupRestoreScenario scenario) { HILOGI("Begin"); - AsyncCallJsOnProcessTask(obj, scenario); - StartOnProcessTimeOutTimer(obj); while (!stopCallJsOnProcess_.load()) { std::unique_lock lock(onProcessLock_); execOnProcessCon_.wait_for(lock, std::chrono::seconds(BConstants::CALL_APP_ON_PROCESS_TIME_INTERVAL), @@ -514,6 +512,10 @@ void BackupExtExtension::ExecCallOnProcessTask(wptr obj, Bac void BackupExtExtension::AsyncCallJsOnProcessTask(wptr obj, BackupRestoreScenario scenario) { HILOGI("Begin"); + if (stopCallJsOnProcess_.load()) { + HILOGE("Current extension execute finished"); + return; + } auto task = [obj, scenario]() { auto extPtr = obj.promote(); if (extPtr == nullptr) { @@ -529,6 +531,10 @@ void BackupExtExtension::AsyncCallJsOnProcessTask(wptr obj, void BackupExtExtension::SyncCallJsOnProcessTask(wptr obj, BackupRestoreScenario scenario) { HILOGI("Begin"); + if (stopCallJsOnProcess_.load()) { + HILOGE("Current extension execute finished"); + return; + } auto callBack = [obj, scenario](ErrCode errCode, const std::string processInfo) { auto extPtr = obj.promote(); if (extPtr == nullptr) { @@ -538,7 +544,7 @@ void BackupExtExtension::SyncCallJsOnProcessTask(wptr obj, B extPtr->CloseOnProcessTimeOutTimer(); extPtr->onProcessTimeout_.store(false); if (extPtr->onProcessTimeoutCnt_.load() > 0) { - HILOGI("onProcess resturn right result, decrease onProcessTimeoutCnt, cnt is:%{public}d", + HILOGI("onProcess execute success, decrease cnt is:%{public}d", extPtr->onProcessTimeoutCnt_.load()); extPtr->onProcessTimeoutCnt_--; } @@ -601,7 +607,7 @@ void BackupExtExtension::StartOnProcessTimeOutTimer(wptr obj } extPtr->onProcessTimeoutCnt_++; extPtr->onProcessTimeout_.store(true); - HILOGE("Extension onProcess timeout, onProcessTimeoutCnt:%{public}d", extPtr->onProcessTimeoutCnt_.load()); + HILOGE("Extension onProcess timeout, Increase cnt:%{public}d", extPtr->onProcessTimeoutCnt_.load()); }; uint32_t timerId = onProcessTimeoutTimer_.Register(timeoutCallback, BConstants::APP_ON_PROCESS_MAX_TIMEOUT, true); onProcessTimeoutTimerId_ = timerId; diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp index 10c388fb5..0e86b3df7 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp @@ -58,7 +58,8 @@ shared_ptr BSessionRestoreAsync::Init(Callbacks callbacks) .onBundleFinished = callbacks.onBundleFinished, .onAllBundlesFinished = callbacks.onAllBundlesFinished, .onResultReport = callbacks.onResultReport, - .onBackupServiceDied = callbacks.onBackupServiceDied}; + .onBackupServiceDied = callbacks.onBackupServiceDied, + .onProcess = callbacks.onProcess}; int32_t res = proxy->InitRestoreSession(sptr(new ServiceReverse(callbacksTmp))); if (res != 0) { HILOGE("Failed to Restore because of %{public}d", res); diff --git a/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp b/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp index dd71f134c..b1b7b6b2b 100644 --- a/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp @@ -89,6 +89,7 @@ ErrCode BSessionRestoreAsync::AppendBundles(UniqueFd remoteCap, vector