From 4bdfd73347aa0f7101d0fc1acecef2d72cae1cdc Mon Sep 17 00:00:00 2001 From: chen0088 Date: Thu, 1 Aug 2024 21:08:35 +0800 Subject: [PATCH 01/10] 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/10] =?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/10] 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/10] 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/10] 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/10] 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/10] 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/10] =?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/10] 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 e9491655cd461d0255eb77bd1347d741f1dc4e84 Mon Sep 17 00:00:00 2001 From: libo429 Date: Tue, 6 Aug 2024 12:57:05 +0800 Subject: [PATCH 10/10] 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