From d1fe934b5157e6111900907fc59ab09e851829bf Mon Sep 17 00:00:00 2001 From: openharmony_ci <120357966@qq.com> Date: Fri, 10 Mar 2023 06:43:48 +0000 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E9=80=80=20'Pull=20Request=20!57=20:?= =?UTF-8?q?=20=E5=A4=87=E4=BB=BD=E6=81=A2=E5=A4=8D=E6=A1=86=E6=9E=B6?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=BC=80=E6=BA=90'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .clang-format | 162 ----- .gitignore | 1 - BUILD.gn | 35 +- backup.gni | 51 -- bundle.json | 27 +- frameworks/js/backup_ext/BUILD.gn | 23 - frameworks/js/backup_ext/ext_backup_impl.cpp | 55 -- frameworks/native/backup_ext/BUILD.gn | 59 -- .../native/backup_ext/include/ext_backup.h | 55 -- .../backup_ext/include/ext_backup_context.h | 36 -- .../native/backup_ext/include/ext_backup_js.h | 142 ----- .../backup_ext/include/ext_backup_loader.h | 38 -- .../native/backup_ext/include/ext_extension.h | 89 --- .../backup_ext/include/ext_extension_stub.h | 45 -- .../native/backup_ext/src/ext_backup.cpp | 47 -- .../native/backup_ext/src/ext_backup_js.cpp | 237 ------- .../backup_ext/src/ext_backup_loader.cpp | 48 -- .../native/backup_ext/src/ext_extension.cpp | 512 --------------- .../backup_ext/src/ext_extension_stub.cpp | 111 ---- .../include/service_reverse.h | 49 -- .../include/service_reverse_stub.h | 49 -- .../backup_kit_inner/src/b_file_info.cpp | 58 -- .../backup_kit_inner/src/b_session_backup.cpp | 97 --- .../src/b_session_restore.cpp | 123 ---- .../backup_kit_inner/src/service_proxy.cpp | 281 --------- .../backup_kit_inner/src/service_reverse.cpp | 115 ---- .../src/service_reverse_stub.cpp | 125 ---- interfaces/api/js/napi/backup_ext/BUILD.gn | 52 -- .../backup_ext/backup_extension_ability.js | 26 - .../native/backup_kit_inner/BUILD.gn | 66 -- .../backup_kit_inner/backup_kit_inner.h | 22 - .../backup_kit_inner/impl/b_file_info.h | 44 -- .../backup_kit_inner/impl/b_session_backup.h | 73 --- .../backup_kit_inner/impl/b_session_restore.h | 95 --- .../backup_kit_inner/impl/i_extension.h | 44 -- .../native/backup_kit_inner/impl/i_service.h | 56 -- .../backup_kit_inner/impl/i_service_reverse.h | 59 -- .../backup_kit_inner/impl/service_proxy.h | 67 -- .../impl/svc_death_recipient.h | 40 -- services/5203.xml | 30 - services/BUILD.gn | 39 -- services/backup.cfg | 11 - services/backup.para | 14 - services/backup_sa/BUILD.gn | 53 -- .../backup_sa/include/module_ipc/service.h | 136 ---- .../module_ipc/service_reverse_proxy.h | 44 -- .../include/module_ipc/service_stub.h | 48 -- .../module_ipc/svc_backup_connection.h | 93 --- .../include/module_ipc/svc_extension_proxy.h | 38 -- .../include/module_ipc/svc_session_manager.h | 252 -------- .../include/module_sched/sched_scheduler.h | 89 --- services/backup_sa/src/module_ipc/service.cpp | 544 ---------------- .../src/module_ipc/service_reverse_proxy.cpp | 153 ----- .../backup_sa/src/module_ipc/service_stub.cpp | 209 ------- .../src/module_ipc/svc_backup_connection.cpp | 101 --- .../src/module_ipc/svc_extension_proxy.cpp | 108 ---- .../src/module_ipc/svc_session_manager.cpp | 428 ------------- .../src/module_sched/sched_scheduler.cpp | 109 ---- .../mock/accesstoken/accesstoken_kit_mock.cpp | 34 - tests/mock/affwk/service_registry_mock.cpp | 65 -- tests/mock/b_filesystem/b_file_mock.cpp | 86 --- tests/mock/b_process/b_process/b_multiuser.h | 42 -- tests/mock/b_process/b_process_mock.cpp | 32 - .../mock/b_tarball/b_tarball_cmdline_mock.cpp | 44 -- .../b_session_backup_mock.cpp | 86 --- .../b_session_restore_mock.cpp | 106 ---- .../backup_kit_inner/service_proxy_mock.cpp | 110 ---- .../include/mock_bundle_manager.h | 62 -- .../src/mock_bundle_manager.cpp | 87 --- tests/mock/module_ipc/service_mock.cpp | 106 ---- .../module_ipc/service_reverse_proxy_mock.cpp | 38 -- tests/mock/module_ipc/service_stub_mock.cpp | 130 ---- .../module_ipc/svc_backup_connection_mock.cpp | 69 --- .../module_ipc/svc_extension_proxy_mock.cpp | 40 -- .../module_ipc/svc_session_manager_mock.cpp | 199 ------ .../module_sched/sched_scheduler_mock.cpp | 32 - tests/mock/parameter/include/parameter.h | 40 -- tests/mock/parameter/src/parameter.c | 50 -- tests/mock/parcel/include/parcel.h | 67 -- tests/mock/parcel/src/parcel.cpp | 97 --- .../service_registry_mock.cpp | 56 -- tests/mock/timer/timer_mock.cpp | 53 -- .../utils_mock/include/iremote_object_mock.h | 86 --- .../include/utils_mock_global_variable.h | 27 - .../src/utils_mock_global_variable.cpp | 54 -- tests/moduletests/BUILD.gn | 24 - tests/moduletests/backup_kit_inner/BUILD.gn | 54 -- .../b_session_backup_test.cpp | 241 -------- .../b_session_restore_test.cpp | 329 ---------- tests/moduletests/backup_tool/BUILD.gn | 37 -- .../backup_tool/tool_backup_restore_test.cpp | 31 - .../backup_tool/tool_help_test.cpp | 78 --- tests/unittests/BUILD.gn | 26 - tests/unittests/backup_api/BUILD.gn | 21 - .../unittests/backup_api/backup_impl/BUILD.gn | 80 --- .../backup_impl/b_file_info_test.cpp | 141 ----- .../backup_impl/include/ext_extension_mock.h | 99 --- .../backup_impl/include/i_service_mock.h | 99 --- .../include/service_reverse_mock.h | 50 -- .../backup_impl/service_proxy_test.cpp | 350 ----------- .../backup_impl/service_reverse_stub_test.cpp | 363 ----------- .../backup_impl/service_reverse_test.cpp | 352 ----------- .../backup_impl/svc_death_recipient_test.cpp | 62 -- tests/unittests/backup_sa/BUILD.gn | 21 - tests/unittests/backup_sa/module_ipc/BUILD.gn | 175 ------ .../module_ipc/sched_scheduler_test.cpp | 166 ----- .../module_ipc/service_reverse_proxy_test.cpp | 263 -------- .../module_ipc/service_stub_test.cpp | 362 ----------- .../backup_sa/module_ipc/service_test.cpp | 463 -------------- .../module_ipc/svc_backup_connection_test.cpp | 178 ------ .../module_ipc/svc_extension_proxy_test.cpp | 147 ----- .../module_ipc/svc_session_manager_test.cpp | 479 -------------- tests/unittests/backup_tools/BUILD.gn | 95 --- .../backup_tool/tools_op_backup_test.cpp | 189 ------ .../backup_tool/tools_op_check_sa_test.cpp | 72 --- .../backup_tool/tools_op_restore_test.cpp | 146 ----- .../backup_tool/tools_op_test.cpp | 96 --- tests/unittests/backup_utils/BUILD.gn | 136 ---- .../backup_utils/b_error/b_error_test.cpp | 183 ------ .../backup_utils/b_filesystem/b_dir_test.cpp | 182 ------ .../backup_utils/b_filesystem/b_file_test.cpp | 134 ---- .../b_json/b_json_cached_entity_test.cpp | 144 ----- .../b_json/b_json_entity_ext_manage_test.cpp | 532 ---------------- .../b_json_entity_extension_config_test.cpp | 582 ------------------ .../backup_utils/b_process/b_process_test.cpp | 79 --- .../b_tarball/b_tarball_cmdline_test.cpp | 149 ----- .../b_tarball/b_tarball_factory_test.cpp | 67 -- tests/utils/BUILD.gn | 34 - tests/utils/include/test_manager.h | 39 -- tests/utils/src/test_manager.cpp | 42 -- tools/backup_tool/BUILD.gn | 45 -- tools/backup_tool/include/tools_op.h | 121 ---- tools/backup_tool/src/main.cpp | 99 --- tools/backup_tool/src/tools_op.cpp | 87 --- tools/backup_tool/src/tools_op_backup.cpp | 289 --------- tools/backup_tool/src/tools_op_check_sa.cpp | 53 -- tools/backup_tool/src/tools_op_help.cpp | 62 -- tools/backup_tool/src/tools_op_restore.cpp | 289 --------- utils/BUILD.gn | 68 -- utils/include/b_encryption/b_encryption.h | 23 - utils/include/b_error/b_error.h | 234 ------- utils/include/b_filesystem/b_dir.h | 55 -- utils/include/b_filesystem/b_file.h | 68 -- utils/include/b_json/b_json_cached_entity.h | 161 ----- utils/include/b_json/b_json_entity.h | 57 -- utils/include/b_json/b_json_entity_caps.h | 87 --- .../include/b_json/b_json_entity_ext_manage.h | 80 --- .../b_json/b_json_entity_extension_config.h | 65 -- utils/include/b_ohos/startup/backup_para.h | 31 - utils/include/b_process/b_guard_cwd.h | 51 -- utils/include/b_process/b_guard_signal.h | 52 -- utils/include/b_process/b_multiuser.h | 40 -- utils/include/b_process/b_process.h | 54 -- utils/include/b_resources/b_constants.h | 134 ---- utils/include/b_tarball/b_tarball_cmdline.h | 40 -- utils/include/b_tarball/b_tarball_factory.h | 77 --- utils/src/b_encryption/b_encryption.cpp | 27 - utils/src/b_error/b_error.cpp | 67 -- utils/src/b_filesystem/b_dir.cpp | 179 ------ utils/src/b_filesystem/b_file.cpp | 139 ----- utils/src/b_ipc/b_want_2_ext.cpp | 30 - utils/src/b_json/b_json_entity_ext_manage.cpp | 215 ------- .../b_json/b_json_entity_extension_config.cpp | 128 ---- utils/src/b_ohos/startup/backup_para.cpp | 68 -- utils/src/b_process/b_guard_cwd.cpp | 42 -- utils/src/b_process/b_guard_signal.cpp | 41 -- utils/src/b_process/b_process.cpp | 116 ---- utils/src/b_tarball/b_tarball_cmdline.cpp | 91 --- utils/src/b_tarball/b_tarball_factory.cpp | 181 ------ 169 files changed, 3 insertions(+), 19046 deletions(-) delete mode 100644 .clang-format delete mode 100644 .gitignore delete mode 100644 backup.gni delete mode 100644 frameworks/js/backup_ext/BUILD.gn delete mode 100644 frameworks/js/backup_ext/ext_backup_impl.cpp delete mode 100644 frameworks/native/backup_ext/BUILD.gn delete mode 100644 frameworks/native/backup_ext/include/ext_backup.h delete mode 100644 frameworks/native/backup_ext/include/ext_backup_context.h delete mode 100644 frameworks/native/backup_ext/include/ext_backup_js.h delete mode 100644 frameworks/native/backup_ext/include/ext_backup_loader.h delete mode 100644 frameworks/native/backup_ext/include/ext_extension.h delete mode 100644 frameworks/native/backup_ext/include/ext_extension_stub.h delete mode 100644 frameworks/native/backup_ext/src/ext_backup.cpp delete mode 100644 frameworks/native/backup_ext/src/ext_backup_js.cpp delete mode 100644 frameworks/native/backup_ext/src/ext_backup_loader.cpp delete mode 100644 frameworks/native/backup_ext/src/ext_extension.cpp delete mode 100644 frameworks/native/backup_ext/src/ext_extension_stub.cpp delete mode 100644 frameworks/native/backup_kit_inner/include/service_reverse.h delete mode 100644 frameworks/native/backup_kit_inner/include/service_reverse_stub.h delete mode 100644 frameworks/native/backup_kit_inner/src/b_file_info.cpp delete mode 100644 frameworks/native/backup_kit_inner/src/b_session_backup.cpp delete mode 100644 frameworks/native/backup_kit_inner/src/b_session_restore.cpp delete mode 100644 frameworks/native/backup_kit_inner/src/service_proxy.cpp delete mode 100644 frameworks/native/backup_kit_inner/src/service_reverse.cpp delete mode 100644 frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp delete mode 100644 interfaces/api/js/napi/backup_ext/BUILD.gn delete mode 100644 interfaces/api/js/napi/backup_ext/backup_extension_ability.js delete mode 100644 interfaces/inner_api/native/backup_kit_inner/BUILD.gn delete mode 100644 interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/b_file_info.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/i_service.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h delete mode 100644 interfaces/inner_api/native/backup_kit_inner/impl/svc_death_recipient.h delete mode 100644 services/5203.xml delete mode 100644 services/BUILD.gn delete mode 100644 services/backup.cfg delete mode 100644 services/backup.para delete mode 100644 services/backup_sa/BUILD.gn delete mode 100644 services/backup_sa/include/module_ipc/service.h delete mode 100644 services/backup_sa/include/module_ipc/service_reverse_proxy.h delete mode 100644 services/backup_sa/include/module_ipc/service_stub.h delete mode 100644 services/backup_sa/include/module_ipc/svc_backup_connection.h delete mode 100644 services/backup_sa/include/module_ipc/svc_extension_proxy.h delete mode 100644 services/backup_sa/include/module_ipc/svc_session_manager.h delete mode 100644 services/backup_sa/include/module_sched/sched_scheduler.h delete mode 100644 services/backup_sa/src/module_ipc/service.cpp delete mode 100644 services/backup_sa/src/module_ipc/service_reverse_proxy.cpp delete mode 100644 services/backup_sa/src/module_ipc/service_stub.cpp delete mode 100644 services/backup_sa/src/module_ipc/svc_backup_connection.cpp delete mode 100644 services/backup_sa/src/module_ipc/svc_extension_proxy.cpp delete mode 100644 services/backup_sa/src/module_ipc/svc_session_manager.cpp delete mode 100644 services/backup_sa/src/module_sched/sched_scheduler.cpp delete mode 100644 tests/mock/accesstoken/accesstoken_kit_mock.cpp delete mode 100644 tests/mock/affwk/service_registry_mock.cpp delete mode 100644 tests/mock/b_filesystem/b_file_mock.cpp delete mode 100644 tests/mock/b_process/b_process/b_multiuser.h delete mode 100644 tests/mock/b_process/b_process_mock.cpp delete mode 100644 tests/mock/b_tarball/b_tarball_cmdline_mock.cpp delete mode 100644 tests/mock/backup_kit_inner/b_session_backup_mock.cpp delete mode 100644 tests/mock/backup_kit_inner/b_session_restore_mock.cpp delete mode 100644 tests/mock/backup_kit_inner/service_proxy_mock.cpp delete mode 100644 tests/mock/bundle_manager/include/mock_bundle_manager.h delete mode 100644 tests/mock/bundle_manager/src/mock_bundle_manager.cpp delete mode 100644 tests/mock/module_ipc/service_mock.cpp delete mode 100644 tests/mock/module_ipc/service_reverse_proxy_mock.cpp delete mode 100644 tests/mock/module_ipc/service_stub_mock.cpp delete mode 100644 tests/mock/module_ipc/svc_backup_connection_mock.cpp delete mode 100644 tests/mock/module_ipc/svc_extension_proxy_mock.cpp delete mode 100644 tests/mock/module_ipc/svc_session_manager_mock.cpp delete mode 100644 tests/mock/module_sched/sched_scheduler_mock.cpp delete mode 100644 tests/mock/parameter/include/parameter.h delete mode 100644 tests/mock/parameter/src/parameter.c delete mode 100644 tests/mock/parcel/include/parcel.h delete mode 100644 tests/mock/parcel/src/parcel.cpp delete mode 100644 tests/mock/system_ability_manager/service_registry_mock.cpp delete mode 100644 tests/mock/timer/timer_mock.cpp delete mode 100644 tests/mock/utils_mock/include/iremote_object_mock.h delete mode 100644 tests/mock/utils_mock/include/utils_mock_global_variable.h delete mode 100644 tests/mock/utils_mock/src/utils_mock_global_variable.cpp delete mode 100644 tests/moduletests/BUILD.gn delete mode 100644 tests/moduletests/backup_kit_inner/BUILD.gn delete mode 100644 tests/moduletests/backup_kit_inner/b_session_backup_test.cpp delete mode 100644 tests/moduletests/backup_kit_inner/b_session_restore_test.cpp delete mode 100644 tests/moduletests/backup_tool/BUILD.gn delete mode 100644 tests/moduletests/backup_tool/tool_backup_restore_test.cpp delete mode 100644 tests/moduletests/backup_tool/tool_help_test.cpp delete mode 100644 tests/unittests/BUILD.gn delete mode 100644 tests/unittests/backup_api/BUILD.gn delete mode 100644 tests/unittests/backup_api/backup_impl/BUILD.gn delete mode 100644 tests/unittests/backup_api/backup_impl/b_file_info_test.cpp delete mode 100644 tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h delete mode 100644 tests/unittests/backup_api/backup_impl/include/i_service_mock.h delete mode 100644 tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h delete mode 100644 tests/unittests/backup_api/backup_impl/service_proxy_test.cpp delete mode 100644 tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp delete mode 100644 tests/unittests/backup_api/backup_impl/service_reverse_test.cpp delete mode 100644 tests/unittests/backup_api/backup_impl/svc_death_recipient_test.cpp delete mode 100644 tests/unittests/backup_sa/BUILD.gn delete mode 100644 tests/unittests/backup_sa/module_ipc/BUILD.gn delete mode 100644 tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp delete mode 100644 tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp delete mode 100644 tests/unittests/backup_sa/module_ipc/service_stub_test.cpp delete mode 100644 tests/unittests/backup_sa/module_ipc/service_test.cpp delete mode 100644 tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp delete mode 100644 tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp delete mode 100644 tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp delete mode 100644 tests/unittests/backup_tools/BUILD.gn delete mode 100644 tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp delete mode 100644 tests/unittests/backup_tools/backup_tool/tools_op_check_sa_test.cpp delete mode 100644 tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp delete mode 100644 tests/unittests/backup_tools/backup_tool/tools_op_test.cpp delete mode 100644 tests/unittests/backup_utils/BUILD.gn delete mode 100644 tests/unittests/backup_utils/b_error/b_error_test.cpp delete mode 100644 tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp delete mode 100644 tests/unittests/backup_utils/b_filesystem/b_file_test.cpp delete mode 100644 tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp delete mode 100644 tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp delete mode 100644 tests/unittests/backup_utils/b_json/b_json_entity_extension_config_test.cpp delete mode 100644 tests/unittests/backup_utils/b_process/b_process_test.cpp delete mode 100644 tests/unittests/backup_utils/b_tarball/b_tarball_cmdline_test.cpp delete mode 100644 tests/unittests/backup_utils/b_tarball/b_tarball_factory_test.cpp delete mode 100644 tests/utils/BUILD.gn delete mode 100644 tests/utils/include/test_manager.h delete mode 100644 tests/utils/src/test_manager.cpp delete mode 100644 tools/backup_tool/BUILD.gn delete mode 100644 tools/backup_tool/include/tools_op.h delete mode 100644 tools/backup_tool/src/main.cpp delete mode 100644 tools/backup_tool/src/tools_op.cpp delete mode 100644 tools/backup_tool/src/tools_op_backup.cpp delete mode 100644 tools/backup_tool/src/tools_op_check_sa.cpp delete mode 100644 tools/backup_tool/src/tools_op_help.cpp delete mode 100644 tools/backup_tool/src/tools_op_restore.cpp delete mode 100644 utils/BUILD.gn delete mode 100644 utils/include/b_encryption/b_encryption.h delete mode 100644 utils/include/b_error/b_error.h delete mode 100644 utils/include/b_filesystem/b_dir.h delete mode 100644 utils/include/b_filesystem/b_file.h delete mode 100644 utils/include/b_json/b_json_cached_entity.h delete mode 100644 utils/include/b_json/b_json_entity.h delete mode 100644 utils/include/b_json/b_json_entity_caps.h delete mode 100644 utils/include/b_json/b_json_entity_ext_manage.h delete mode 100644 utils/include/b_json/b_json_entity_extension_config.h delete mode 100644 utils/include/b_ohos/startup/backup_para.h delete mode 100644 utils/include/b_process/b_guard_cwd.h delete mode 100644 utils/include/b_process/b_guard_signal.h delete mode 100644 utils/include/b_process/b_multiuser.h delete mode 100644 utils/include/b_process/b_process.h delete mode 100644 utils/include/b_resources/b_constants.h delete mode 100644 utils/include/b_tarball/b_tarball_cmdline.h delete mode 100644 utils/include/b_tarball/b_tarball_factory.h delete mode 100644 utils/src/b_encryption/b_encryption.cpp delete mode 100644 utils/src/b_error/b_error.cpp delete mode 100644 utils/src/b_filesystem/b_dir.cpp delete mode 100644 utils/src/b_filesystem/b_file.cpp delete mode 100644 utils/src/b_ipc/b_want_2_ext.cpp delete mode 100644 utils/src/b_json/b_json_entity_ext_manage.cpp delete mode 100644 utils/src/b_json/b_json_entity_extension_config.cpp delete mode 100644 utils/src/b_ohos/startup/backup_para.cpp delete mode 100644 utils/src/b_process/b_guard_cwd.cpp delete mode 100644 utils/src/b_process/b_guard_signal.cpp delete mode 100644 utils/src/b_process/b_process.cpp delete mode 100644 utils/src/b_tarball/b_tarball_cmdline.cpp delete mode 100644 utils/src/b_tarball/b_tarball_factory.cpp diff --git a/.clang-format b/.clang-format deleted file mode 100644 index 286ddac76..000000000 --- a/.clang-format +++ /dev/null @@ -1,162 +0,0 @@ -Language: Cpp -# BasedOnStyle: LLVM -# 访问说明符(public、private等)的偏移 -AccessModifierOffset: -4 -# 开括号(开圆括号、开尖括号、开方括号)后的对齐 -AlignAfterOpenBracket: Align -# 连续赋值时,等号对齐 -AlignConsecutiveAssignments: false -# 连续赋值时,变量名对齐 -AlignConsecutiveDeclarations: false -# 左对齐逃脱换行(使用反斜杠换行)的反斜杠 -AlignEscapedNewlinesLeft: true -# 水平对齐二元和三元表达式的操作数 -AlignOperands: true -# 对齐连续的尾随的注释 -AlignTrailingComments: true -# 允许函数声明的所有参数在放在下一行 -AllowAllParametersOfDeclarationOnNextLine: false -# 允许短的块放在同一行 -AllowShortBlocksOnASingleLine: false -# 允许短的case标签放在同一行 -AllowShortCaseLabelsOnASingleLine: false -# 允许短的函数放在同一行: None, InlineOnly(定义在类中), Empty(空函数), Inline(定义在类中,空函数), All -AllowShortFunctionsOnASingleLine: Empty -# 允许短的if语句保持在同一行 -AllowShortIfStatementsOnASingleLine: false -# 允许短的循环保持在同一行 -AllowShortLoopsOnASingleLine: false -# 总是在定义返回类型后换行(deprecated) -AlwaysBreakAfterDefinitionReturnType: None -# 总是在返回类型后换行: None, All, TopLevel(顶级函数,不包括在类中的函数), -# AllDefinitions(所有的定义,不包括声明), TopLevelDefinitions(所有的顶级函数的定义) -AlwaysBreakAfterReturnType: None -# 总是在多行string字面量前换行 -AlwaysBreakBeforeMultilineStrings: true -# 总是在template声明后换行 -AlwaysBreakTemplateDeclarations: true -# false表示函数实参要么都在同一行,要么都各自一行 -BinPackArguments: true -# false表示所有形参要么都在同一行,要么都各自一行 -BinPackParameters: false -# 大括号换行,只有当BreakBeforeBraces设置为Custom时才有效 -BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: true - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false -# 在二元运算符前换行: None(在操作符后换行), NonAssignment(在非赋值的操作符前换行), All(在操作符前换行) -BreakBeforeBinaryOperators: None -# 在大括号前换行: Attach(始终将大括号附加到周围的上下文), Linux(除函数、命名空间和类定义,与Attach类似), -# Mozilla(除枚举、函数、记录定义,与Attach类似), Stroustrup(除函数定义、catch、else,与Attach类似), -# Allman(总是在大括号前换行), GNU(总是在大括号前换行,并对于控制语句的大括号增加额外的缩进), WebKit(在函数前换行), Custom -# 注:这里认为语句块也属于函数 -BreakBeforeBraces: Custom -# 在三元运算符前换行 -BreakBeforeTernaryOperators: true -# 在构造函数的初始化列表的逗号前换行 -BreakConstructorInitializersBeforeComma: false -# 每行字符的限制,0表示没有限制 -ColumnLimit: 120 -# 描述具有特殊意义的注释的正则表达式,它不应该被分割为多行或以其它方式改变 -CommentPragmas: "^ IWYU pragma:" -# 构造函数的初始化列表要么都在同一行,要么都各自一行 -ConstructorInitializerAllOnOneLineOrOnePerLine: true -# 构造函数的初始化列表的缩进宽度 -ConstructorInitializerIndentWidth: 4 -# 延续的行的缩进宽度 -ContinuationIndentWidth: 4 -# 去除C++11的列表初始化的大括号{后和}前的空格 -Cpp11BracedListStyle: true -# 继承最常用的指针和引用的对齐方式 -DerivePointerAlignment: false -# 关闭格式化 -DisableFormat: false -# 自动检测函数的调用和定义是否被格式为每行一个参数(Experimental) -ExperimentalAutoDetectBinPacking: false -# 需要被解读为foreach循环而不是函数调用的宏 -ForEachMacros: [foreach, Q_FOREACH, BOOST_FOREACH] -# 对#include进行排序,匹配了某正则表达式的#include拥有对应的优先级,匹配不到的则默认优先级为INT_MAX(优先级越小排序越靠前), -# 可以定义负数优先级从而保证某些#include永远在最前面 -IncludeCategories: - - Regex: '^"(llvm|llvm-c|clang|clang-c)/' - Priority: 2 - - Regex: '^(<|"(gtest|isl|json)/)' - Priority: 3 - - Regex: ".*" - Priority: 1 -# 缩进case标签 -IndentCaseLabels: true -# 缩进宽度 -IndentWidth: 4 -# 函数返回类型换行时,缩进函数声明或函数定义的函数名 -IndentWrappedFunctionNames: true -# 保留在块开始处的空行 -KeepEmptyLinesAtTheStartOfBlocks: true -# 开始一个块的宏的正则表达式 -MacroBlockBegin: "" -# 结束一个块的宏的正则表达式 -MacroBlockEnd: "" -# 连续空行的最大数量 -MaxEmptyLinesToKeep: 1 -# 命名空间的缩进: None, Inner(缩进嵌套的命名空间中的内容), All -NamespaceIndentation: None -# 使用ObjC块时缩进宽度 -ObjCBlockIndentWidth: 4 -# 在ObjC的@property后添加一个空格 -ObjCSpaceAfterProperty: false -# 在ObjC的protocol列表前添加一个空格 -ObjCSpaceBeforeProtocolList: true -# 在call(后对函数调用换行的penalty -PenaltyBreakBeforeFirstCallParameter: 19 -# 在一个注释中引入换行的penalty -PenaltyBreakComment: 300 -# 第一次在<<前换行的penalty -PenaltyBreakFirstLessLess: 120 -# 在一个字符串字面量中引入换行的penalty -PenaltyBreakString: 1000 -# 对于每个在行字符数限制之外的字符的penalty -PenaltyExcessCharacter: 1000000 -# 将函数的返回类型放到它自己的行的penalty -PenaltyReturnTypeOnItsOwnLine: 120 -# 指针和引用的对齐: Left, Right, Middle -PointerAlignment: Right -# 允许重新排版注释 -ReflowComments: true -# 允许排序#include -SortIncludes: true -# 在C风格类型转换后添加空格 -SpaceAfterCStyleCast: false -# 在赋值运算符之前添加空格 -SpaceBeforeAssignmentOperators: true -# 开圆括号之前添加一个空格: Never, ControlStatements, Always -SpaceBeforeParens: ControlStatements -# 在空的圆括号中添加空格 -SpaceInEmptyParentheses: false -# 在尾随的评论前添加的空格数(只适用于//) -SpacesBeforeTrailingComments: 1 -# 在尖括号的<后和>前添加空格 -SpacesInAngles: false -# 在容器(ObjC和JavaScript的数组和字典等)字面量中添加空格 -SpacesInContainerLiterals: true -# 在C风格类型转换的括号中添加空格 -SpacesInCStyleCastParentheses: false -# 在圆括号的(后和)前添加空格 -SpacesInParentheses: false -# 在方括号的[后和]前添加空格,lamda表达式和未指明大小的数组的声明不受影响 -SpacesInSquareBrackets: false -# 在C++11的列表初始化的大括号之前添加空格 -SpaceBeforeCpp11BracedList: true -# 标准: c++03,c++11,c++14,c++17,c++20,Latest,Auto -Standard: c++17 -# tab宽度 -TabWidth: 4 -# 使用tab字符: Never, ForIndentation, ForContinuationAndIndentation, Always -UseTab: Never \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 600d2d33b..000000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.vscode \ No newline at end of file diff --git a/BUILD.gn b/BUILD.gn index c51710244..4233fa935 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -20,36 +20,3 @@ group("libremotefileshare") { "//foundation/filemanagement/app_file_service/interfaces/kits/js:remotefileshare", ] } - -group("tgt_backup_extension") { - deps = [ - "frameworks/native/backup_ext:backup_extension_ability_native", - "interfaces/api/js/napi/backup_ext:backupextensionability_napi", - ] -} - -group("tgt_backup_kit_inner") { - deps = [ "interfaces/inner_api/native/backup_kit_inner" ] -} - -group("tgt_backup_sa") { - deps = [ - "services:backup_para_etc", - "services:backup_sa_etc", - "services:backup_sa_profile", - "services/backup_sa", - ] -} - -group("tgt_backup_tool") { - deps = [ "tools/backup_tool" ] -} - -group("tgt_backup_tests") { - testonly = true - - deps = [ - "tests/moduletests", - "tests/unittests", - ] -} diff --git a/backup.gni b/backup.gni deleted file mode 100644 index 7dc5c0e87..000000000 --- a/backup.gni +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -path_backup = "//foundation/filemanagement/app_file_service" -path_module_out_tests = "filemanagement/app_file_service/backup" - -path_ability_runtime = "//foundation/ability/ability_runtime" -path_access_token = "//base/security/access_token" -path_base = "//commonlibrary/c_utils/base" -path_distributedfile = "//foundation/distributeddatamgr/distributedfile" -path_faultloggerd = "//base/hiviewdfx/faultloggerd" -path_googletest = "//third_party/googletest" -path_ipc = "//foundation/communication/ipc" -path_jsoncpp = "//third_party/jsoncpp" -path_napi = "//foundation/arkui/napi" -path_samgr = "//foundation/systemabilitymgr/samgr" -path_init = "//base/startup/init" - -path_backup_mock = "//foundation/filemanagement/app_file_service/tests/mock" - -backup_mock_parcel_include_dirs = [ "$path_backup_mock/parcel/include" ] -backup_mock_parcel_src = [ "$path_backup_mock/parcel/src/parcel.cpp" ] -backup_mock_parameter_include_dirs = [ "$path_backup_mock/parameter/include" ] -backup_mock_parameter_src = [ "$path_backup_mock/parameter/src/parameter.c" ] -backup_mock_src = [ - "$path_backup_mock/module_ipc/service_reverse_proxy_mock.cpp", - "$path_backup_mock/module_ipc/service_stub_mock.cpp", - "$path_backup_mock/module_ipc/svc_backup_connection_mock.cpp", - "$path_backup_mock/module_ipc/svc_extension_proxy_mock.cpp", -] -backup_mock_session_manager_src = - [ "$path_backup_mock/module_ipc/svc_session_manager_mock.cpp" ] -backup_mock_scheduler_src = - [ "$path_backup_mock/module_sched/sched_scheduler_mock.cpp" ] -backup_mock_service_src = [ "$path_backup_mock/module_ipc/service_mock.cpp" ] -backup_mock_utils_include = [ "$path_backup_mock/utils_mock/include" ] -backup_mock_proxy_src = [ - "$path_backup_mock/backup_kit_inner/service_proxy_mock.cpp", - "$path_backup_mock/utils_mock/src/utils_mock_global_variable.cpp", - "$path_backup/frameworks/native/backup_kit_inner/src/b_file_info.cpp", -] diff --git a/bundle.json b/bundle.json index db5b7394e..fa6637b89 100644 --- a/bundle.json +++ b/bundle.json @@ -14,8 +14,7 @@ "name": "app_file_service", "subsystem": "filemanagement", "syscap": [ - "SystemCapability.FileManagement.RemoteFileShare", - "SystemCapability.FileManagement.StorageService.Backup" + "SystemCapability.FileManagement.RemoteFileShare" ], "adapted_system_type": [ "standard" @@ -32,12 +31,6 @@ ], "service_group": [] }, - "sub_component": [ - "//foundation/filemanagement/app_file_service:tgt_backup_extension", - "//foundation/filemanagement/app_file_service:tgt_backup_kit_inner", - "//foundation/filemanagement/app_file_service:tgt_backup_sa", - "//foundation/filemanagement/app_file_service:tgt_backup_tool" - ], "inner_kits": [ { "name": "//foundation/filemanagement/app_file_service/interfaces/innerkits/native/file_share:fileshare_native", @@ -56,27 +49,11 @@ ], "header_base": "//foundation/filemanagement/app_file_service/interfaces/innerkits/remote_file_share/native" } - }, - { - "name": "//foundation/filemanagement/app_file_service/interfaces/inner_api/native/backup_kit_inner:backup_kit_inner", - "header": { - "header_base": "//foundation/filemanagement/app_file_service/interfaces/inner_api/native/backup_kit_inner", - "header_files": [ - "backup_kit_inner.h", - "impl/b_session_restore.h", - "impl/b_file_info.h", - "impl/service_proxy.h", - "impl/b_session_backup.h", - "impl/i_service.h", - "impl/i_service_reverse.h" - ] - } } ], "test": [ "//foundation/filemanagement/app_file_service/test/fuzztest:fuzztest", - "//foundation/filemanagement/app_file_service/test/unittest:unittest", - "//foundation/filemanagement/app_file_service:tgt_backup_tests" + "//foundation/filemanagement/app_file_service/test/unittest:unittest" ] } } diff --git a/frameworks/js/backup_ext/BUILD.gn b/frameworks/js/backup_ext/BUILD.gn deleted file mode 100644 index 313ae8e6c..000000000 --- a/frameworks/js/backup_ext/BUILD.gn +++ /dev/null @@ -1,23 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -ohos_static_library("backupextensionability_napi_fwk") { - sources = [ "ext_backup_impl.cpp" ] - - external_deps = [ "napi:ace_napi" ] - - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/frameworks/js/backup_ext/ext_backup_impl.cpp b/frameworks/js/backup_ext/ext_backup_impl.cpp deleted file mode 100644 index 41df04d11..000000000 --- a/frameworks/js/backup_ext/ext_backup_impl.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "native_engine/native_engine.h" - -extern const char _binary_backup_extension_ability_js_start[]; -extern const char _binary_backup_extension_ability_js_end[]; -extern const char _binary_backup_extension_ability_abc_start[]; -extern const char _binary_backup_extension_ability_abc_end[]; - -extern "C" __attribute__((constructor)) void NAPI_application_BackupExtensionAbility_AutoRegister() -{ - auto moduleManager = NativeModuleManager::GetInstance(); - NativeModule newModuleInfo = { - .name = "application.BackupExtensionAbility", - .fileName = "application/libbackupextensionability_napi.so/BackupExtensionAbility.js", - }; - - moduleManager->Register(&newModuleInfo); -} - -extern "C" __attribute__((visibility("default"))) void - NAPI_application_BackupExtensionAbility_GetJSCode(const char **buf, int *bufLen) -{ - if (buf != nullptr) { - *buf = _binary_backup_extension_ability_js_start; - } - - if (bufLen != nullptr) { - *bufLen = _binary_backup_extension_ability_js_end - _binary_backup_extension_ability_js_start; - } -} - -extern "C" __attribute__((visibility("default"))) void - NAPI_application_BackupExtensionAbility_GetABCCode(const char **buf, int *buflen) -{ - if (buf != nullptr) { - *buf = _binary_backup_extension_ability_abc_start; - } - if (buflen != nullptr) { - *buflen = _binary_backup_extension_ability_abc_end - _binary_backup_extension_ability_abc_start; - } -} \ No newline at end of file diff --git a/frameworks/native/backup_ext/BUILD.gn b/frameworks/native/backup_ext/BUILD.gn deleted file mode 100644 index 1a0e6fc48..000000000 --- a/frameworks/native/backup_ext/BUILD.gn +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_shared_library("backup_extension_ability_native") { - sources = [ - "src/ext_backup.cpp", - "src/ext_backup_js.cpp", - "src/ext_backup_loader.cpp", - "src/ext_extension.cpp", - "src/ext_extension_stub.cpp", - ] - - defines = [ - "LOG_DOMAIN=0xD004301", - "LOG_TAG=\"BackupExt\"", - ] - - include_dirs = [ - "include", - "${path_napi}/native_engine", - "${path_ability_runtime}/services/common/include", - "${path_ability_runtime}/interfaces/kits/napi/aafwk/inner/napi_common", - "${path_ability_runtime}/interfaces/kits/native/appkit/ability_runtime", - ] - - deps = [ - "${path_ability_runtime}/frameworks/native/appkit:appkit_native", - "${path_backup}/utils:backup_utils", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_context_native", - "ability_runtime:abilitykit_native", - "ability_runtime:app_context", - "ability_runtime:runtime", - "access_token:libaccesstoken_sdk", - "app_file_service:backup_kit_inner", - "bundle_framework:appexecfwk_core", - ] - - use_exceptions = true - relative_install_dir = "extensionability" - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h deleted file mode 100644 index 6977778af..000000000 --- a/frameworks/native/backup_ext/include/ext_backup.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_EXT_BACKUP_H -#define OHOS_FILEMGMT_BACKUP_EXT_BACKUP_H - -#include "ext_backup_context.h" -#include "extension_base.h" -#include "runtime.h" - -namespace OHOS::FileManagement::Backup { -class ExtBackup : public AbilityRuntime::ExtensionBase { -public: - /** - * @brief Init the extension. - * - * @param record the extension record. - * @param application the application info. - * @param handler the extension handler. - * @param token the remote token. - */ - void Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) override; - - /** - * @brief Create Extension. - * - * @param runtime The runtime. - * @return The ServiceExtension instance. - */ - static ExtBackup *Create(const std::unique_ptr &runtime); - -public: - ExtBackup() = default; - ~ExtBackup() override = default; - -private: -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_EXT_BACKUP_H \ No newline at end of file diff --git a/frameworks/native/backup_ext/include/ext_backup_context.h b/frameworks/native/backup_ext/include/ext_backup_context.h deleted file mode 100644 index f8b8d503a..000000000 --- a/frameworks/native/backup_ext/include/ext_backup_context.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_EXT_BACKUP_CONTEXT_H -#define OHOS_FILEMGMT_BACKUP_EXT_BACKUP_CONTEXT_H - -#include "extension_context.h" - -namespace OHOS::FileManagement::Backup { -class ExtBackupContext : public AbilityRuntime::ExtensionContext { -public: - ExtBackupContext() {}; - ~ExtBackupContext() override = default; - - static inline size_t CONTEXT_TYPE_ID = std::hash {}("extBackupContext"); - -protected: - bool IsContext(size_t contextTypeId) override - { - return contextTypeId == CONTEXT_TYPE_ID || ExtensionContext::IsContext(contextTypeId); - } -}; -} // namespace OHOS::FileManagement::Backup -#endif // OHOS_FILEMGMT_BACKUP_EXT_BACKUP_CONTEXT_H \ No newline at end of file diff --git a/frameworks/native/backup_ext/include/ext_backup_js.h b/frameworks/native/backup_ext/include/ext_backup_js.h deleted file mode 100644 index 6ec330fbd..000000000 --- a/frameworks/native/backup_ext/include/ext_backup_js.h +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_EXT_BACKUP_JS_H -#define OHOS_FILEMGMT_BACKUP_EXT_BACKUP_JS_H - -#include -#include -#include - -#include "b_resources/b_constants.h" -#include "ext_backup.h" -#include "js_runtime.h" -#include "native_reference.h" -#include "native_value.h" -#include "unique_fd.h" -#include "want.h" - -namespace OHOS::FileManagement::Backup { -class ExtBackupJs : public ExtBackup { -public: - /** - * @brief Called when this extension is started. You must override this function if you want to perform some - * initialization operations during extension startup. - * - * This function can be called only once in the entire lifecycle of an extension. - * @param Want Indicates the {@link Want} structure containing startup information about the extension. - */ - void OnStart(const AAFwk::Want &want) override; - - /** - * @brief Init the extension. - * - * @param record the extension record. - * @param application the application info. - * @param handler the extension handler. - * @param token the remote token. - */ - void Init(const std::shared_ptr &record, - const std::shared_ptr &application, - std::shared_ptr &handler, - const sptr &token) override; - - /** - * @brief Called back when Service is started. - * This method can be called only by Service. You can use the StartAbility(ohos.aafwk.content.Want) method to start - * Service. Then the system calls back the current method to use the transferred want parameter to execute its own - * logic. - * - * @param want Indicates the want of Service to start. - * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being - * destroyed, and the value false indicates a normal startup. - * @param startId Indicates the number of times the Service extension has been started. The startId is - * incremented by 1 every time the extension is started. For example, if the extension has been started - * for six times, the value of startId is 6. - */ - void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; - - /** - * @brief Called when this backup extension ability is connected for the first time. - * - * You can override this function to implement your own processing logic. - * - * @param want Indicates the {@link Want} structure containing connection information about the backup - * extension. - * @return Returns a pointer to the sid of the connected backup extension ability. - */ - sptr OnConnect(const AAFwk::Want &want) override; - - /** - * @brief Called when all abilities connected to this Wallpaper extension are disconnected. - * - * You can override this function to implement your own processing logic. - * - */ - void OnDisconnect(const AAFwk::Want &want) override; - -public: - /** - * @brief Create ExtBackupJs. - * - * @param runtime The runtime. - * @return The ExtBackupJs instance. - */ - static ExtBackupJs *Create(const std::unique_ptr &runtime); - - /** - * @brief Get the File Handle object - * - * @param fileName - * @return UniqueFd - */ - UniqueFd GetFileHandle(std::string &fileName); - - /** - * @brief Get the Extension Action object - * - * @return BConstants::ExtensionAction - */ - BConstants::ExtensionAction GetExtensionAction() const; - - /** - * @brief Get the User Config, then check if - * - * @return allowed ro not - */ - bool AllowToBackupRestore() const; - - /** - * @brief Get the user configure - * - * @return user configure - */ - std::string GetUsrConfig() const; - -public: - explicit ExtBackupJs(AbilityRuntime::JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {} - ~ExtBackupJs() override = default; - -private: - std::tuple CallObjectMethod(std::string_view name, - const std::vector &argv = {}); - - AbilityRuntime::JsRuntime &jsRuntime_; - std::unique_ptr jsObj_; - BConstants::ExtensionAction extAction_ {BConstants::ExtensionAction::INVALID}; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_EXT_BACKUP_JS_H \ No newline at end of file diff --git a/frameworks/native/backup_ext/include/ext_backup_loader.h b/frameworks/native/backup_ext/include/ext_backup_loader.h deleted file mode 100644 index bfd59a9ff..000000000 --- a/frameworks/native/backup_ext/include/ext_backup_loader.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_EXT_BACKUP_LOADER_H -#define OHOS_FILEMGMT_BACKUP_EXT_BACKUP_LOADER_H - -#include "extension_module_loader.h" - -namespace OHOS::FileManagement::Backup { -class ExtBackupLoader : public AbilityRuntime::ExtensionModuleLoader, public Singleton { - DECLARE_SINGLETON(ExtBackupLoader); - -public: - /** - * @brief Create Extension. - * - * @param runtime The runtime. - * @return The Extension instance. - */ - AbilityRuntime::Extension *Create(const std::unique_ptr &runtime) const override; - - virtual std::map GetParams() override; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_EXT_BACKUP_LOADER_H \ No newline at end of file diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h deleted file mode 100644 index 9469f3df5..000000000 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_BACKUP_EXT_EXTENSION_H -#define OHOS_FILEMGMT_BACKUP_BACKUP_EXT_EXTENSION_H - -#include -#include - -#include "b_json/b_json_entity_extension_config.h" -#include "b_resources/b_constants.h" -#include "ext_backup_js.h" -#include "ext_extension_stub.h" -#include "thread_pool.h" - -namespace OHOS::FileManagement::Backup { -class BackupExtExtension : public ExtExtensionStub { -public: - UniqueFd GetFileHandle(const std::string &fileName) override; - ErrCode HandleClear() override; - ErrCode PublishFile(const std::string &fileName) override; - ErrCode HandleBackup() override; - -public: - explicit BackupExtExtension(const std::shared_ptr &extension) : extension_(extension) - { - threadPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); - } - ~BackupExtExtension() - { - threadPool_.Stop(); - } - -private: - /** - * @brief verify caller uid - * - */ - void VerifyCaller(); - - /** - * @brief backup - * - * @param usrConfig user configure - */ - int HandleBackup(const BJsonEntityExtensionConfig &usrConfig); - - /** - * @brief restore - * - * @param fileName name of the file that to be untar - */ - int HandleRestore(const string &fileName); - - /** - * @brief Executing Backup Tasks Asynchronously - * - * @param extAction action - * - * @param config user configure - */ - void AsyncTaskBackup(const std::string config); - - /** - * @brief Executing Restoration Tasks Asynchronously - * - */ - void AsyncTaskRestore(); - -private: - std::shared_ptr extension_; - std::vector tars_; - OHOS::ThreadPool threadPool_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_BACKUP_EXT_EXTENSION_H \ No newline at end of file diff --git a/frameworks/native/backup_ext/include/ext_extension_stub.h b/frameworks/native/backup_ext/include/ext_extension_stub.h deleted file mode 100644 index a513bb806..000000000 --- a/frameworks/native/backup_ext/include/ext_extension_stub.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_EXT_EXTENSION_STUB_H -#define OHOS_FILEMGMT_BACKUP_EXT_EXTENSION_STUB_H - -#include - -#include "i_extension.h" -#include "iremote_stub.h" - -namespace OHOS::FileManagement::Backup { -class ExtExtensionStub : public IRemoteStub { -public: - int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - -public: - ExtExtensionStub(); - ~ExtExtensionStub() = default; - -private: - ErrCode CmdGetFileHandle(MessageParcel &data, MessageParcel &reply); - ErrCode CmdHandleClear(MessageParcel &data, MessageParcel &reply); - ErrCode CmdHandleBackup(MessageParcel &data, MessageParcel &reply); - ErrCode CmdPublishFile(MessageParcel &data, MessageParcel &reply); - -private: - using ExtensionInterface = int32_t (ExtExtensionStub::*)(MessageParcel &data, MessageParcel &reply); - std::map opToInterfaceMap_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_EXT_EXTENSION_STUB_H \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp deleted file mode 100644 index a38123042..000000000 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ext_backup.h" - -#include "ext_backup_js.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -void ExtBackup::Init(const shared_ptr &record, - const shared_ptr &application, - shared_ptr &handler, - const sptr &token) -{ - HILOGI("Init the BackupExtensionAbility(Base)"); - AbilityRuntime::ExtensionBase::Init(record, application, handler, token); -} - -ExtBackup *ExtBackup::Create(const unique_ptr &runtime) -{ - HILOGI("Create as an BackupExtensionAbility(Base)"); - if (!runtime) { - return new ExtBackup(); - } - - switch (runtime->GetLanguage()) { - case AbilityRuntime::Runtime::Language::JS: - return ExtBackupJs::Create(runtime); - - default: - return new ExtBackup(); - } -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/ext_backup_js.cpp b/frameworks/native/backup_ext/src/ext_backup_js.cpp deleted file mode 100644 index 2e946b33e..000000000 --- a/frameworks/native/backup_ext/src/ext_backup_js.cpp +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ext_backup_js.h" - -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_json/b_json_cached_entity.h" -#include "b_json/b_json_entity_extension_config.h" -#include "b_resources/b_constants.h" -#include "bundle_mgr_client.h" -#include "ext_extension.h" -#include "filemgmt_libhilog.h" -#include "js_runtime_utils.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void ExtBackupJs::OnStart(const AAFwk::Want &want) -{ - HILOGI("BackupExtensionAbility(JS) was started"); - Extension::OnStart(want); -} - -static string GetSrcPath(const AppExecFwk::AbilityInfo &info) -{ - using AbilityRuntime::Extension; - stringstream ss; - - // API9(stage model) 中通过 $(module)$(name)/$(srcEntrance/(.*$)/(.abc)) 获取自定义插件路径 - if (!info.srcEntrance.empty()) { - ss << info.moduleName << '/' << string(info.srcEntrance, 0, info.srcEntrance.rfind(".")) << ".abc"; - return ss.str(); - } - return ""; -} - -void ExtBackupJs::Init(const shared_ptr &record, - const shared_ptr &application, - shared_ptr &handler, - const sptr &token) -{ - HILOGI("Init the BackupExtensionAbility(JS)"); - try { - ExtBackup::Init(record, application, handler, token); - - if (!abilityInfo_) { - throw BError(BError::Codes::EXT_BROKEN_FRAMEWORK, "Invalid abilityInfo_"); - } - - // 获取应用扩展的 BackupExtensionAbility 的路径 - const AppExecFwk::AbilityInfo &info = *abilityInfo_; - string bundleName = info.bundleName; - string moduleName(info.moduleName + "::" + info.name); - string modulePath = GetSrcPath(info); - int moduleType = static_cast(info.type); - HILOGI("Try to load %{public}s's %{public}s(type %{public}d) from %{public}s", bundleName.c_str(), - moduleName.c_str(), moduleType, modulePath.c_str()); - - // 加载用户扩展 BackupExtensionAbility 到 JS 引擎,并将之暂存在 jsObj_ 中。注意,允许加载失败,往后执行默认逻辑 - AbilityRuntime::HandleScope handleScope(jsRuntime_); - jsObj_ = jsRuntime_.LoadModule(moduleName, modulePath, info.hapPath); - if (jsObj_) { - HILOGI("Wow! Here's a custsom BackupExtensionAbility"); - } else { - HILOGW("Oops! There's no custom BackupExtensionAbility"); - } - } catch (const BError &e) { - HILOGE("%{public}s", e.what()); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - } -} - -[[maybe_unused]] tuple ExtBackupJs::CallObjectMethod(string_view name, - const vector &argv) -{ - HILOGI("Call %{public}s", name.data()); - - if (!jsObj_) { - return {BError(BError::Codes::EXT_BROKEN_FRAMEWORK, "Invalid jsObj_").GetCode(), nullptr}; - } - - AbilityRuntime::HandleScope handleScope(jsRuntime_); - - NativeValue *value = jsObj_->Get(); - NativeObject *obj = AbilityRuntime::ConvertNativeValueTo(value); - if (!obj) { - return {BError(BError::Codes::EXT_INVAL_ARG, "The custom BackupAbilityExtension is required to be an object") - .GetCode(), - nullptr}; - } - - NativeValue *method = obj->GetProperty(name.data()); - if (!method || method->TypeOf() != NATIVE_FUNCTION) { - return {BError(BError::Codes::EXT_INVAL_ARG, string(name).append(" is required to be a function")).GetCode(), - nullptr}; - } - - auto ret = jsRuntime_.GetNativeEngine().CallFunction(value, method, argv.data(), argv.size()); - if (!ret) { - return {BError(BError::Codes::EXT_INVAL_ARG, string(name).append(" raised an exception")).GetCode(), nullptr}; - } - return {BError(BError::Codes::OK).GetCode(), ret}; -} - -void ExtBackupJs::OnCommand(const AAFwk::Want &want, bool restart, int startId) -{ - HILOGI("BackupExtensionAbility(JS) was invoked. restart=%{public}d, startId=%{public}d", restart, startId); - - // REM: 处理返回结果 ret - // REM: 通过杀死进程实现 Stop -} - -ExtBackupJs *ExtBackupJs::Create(const unique_ptr &runtime) -{ - HILOGI("Create as an BackupExtensionAbility(JS)"); - return new ExtBackupJs(static_cast(*runtime)); -} - -string ExtBackupJs::GetUsrConfig() const -{ - vector config; - AppExecFwk::BundleMgrClient client; - const AppExecFwk::AbilityInfo &info = *abilityInfo_; - if (!client.GetProfileFromAbility(info, "ohos.extension.backup", config)) { - throw BError(BError::Codes::EXT_INVAL_ARG, "Failed to invoke the GetProfileFromAbility method."); - } - - return config.empty() ? "" : config[0]; -} - -bool ExtBackupJs::AllowToBackupRestore() const -{ - string usrConfig = GetUsrConfig(); - BJsonCachedEntity cachedEntity(usrConfig); - auto cache = cachedEntity.Structuralize(); - if (cache.GetAllowToBackupRestore()) { - return true; - } - return false; -} - -BConstants::ExtensionAction ExtBackupJs::GetExtensionAction() const -{ - return extAction_; -} - -static BConstants::ExtensionAction VerifyAndGetAction(const AAFwk::Want &want, - std::shared_ptr abilityInfo) -{ - if (!abilityInfo) { - string pendingMsg = "Received an empty ability. You must missed the init proc"; - throw BError(BError::Codes::EXT_INVAL_ARG, pendingMsg); - } - - using namespace BConstants; - ExtensionAction extAction {want.GetIntParam(EXTENSION_ACTION_PARA, static_cast(ExtensionAction::INVALID))}; - if (extAction == ExtensionAction::INVALID) { - int extActionInt = static_cast(extAction); - string pendingMsg = string("Want must specify a valid action instead of ").append(to_string(extActionInt)); - throw BError(BError::Codes::EXT_INVAL_ARG, pendingMsg); - } - - return extAction; -} - -sptr ExtBackupJs::OnConnect(const AAFwk::Want &want) -{ - try { - HILOGI("begin"); - // 发起者必须是备份服务 - auto extAction = VerifyAndGetAction(want, abilityInfo_); - if (extAction_ != BConstants::ExtensionAction::INVALID && extAction == BConstants::ExtensionAction::INVALID && - extAction_ != extAction) { - HILOGI("Verification failed."); - return nullptr; - } - // 应用必须配置支持备份恢复 - if (!AllowToBackupRestore()) { - HILOGI("The application does not allow to backup and restore."); - return nullptr; - } - extAction_ = extAction; - - Extension::OnConnect(want); - - auto remoteObject = - sptr(new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); - HILOGI("end"); - return remoteObject->AsObject(); - } catch (const BError &e) { - return nullptr; - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - return nullptr; - } catch (...) { - HILOGE(""); - return nullptr; - } -} - -void ExtBackupJs::OnDisconnect(const AAFwk::Want &want) -{ - try { - HILOGI("begin"); - Extension::OnDisconnect(want); - extAction_ = BConstants::ExtensionAction::INVALID; - HILOGI("end"); - } catch (const BError &e) { - return; - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - return; - } catch (...) { - HILOGE(""); - return; - } -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/ext_backup_loader.cpp b/frameworks/native/backup_ext/src/ext_backup_loader.cpp deleted file mode 100644 index 05cc3330a..000000000 --- a/frameworks/native/backup_ext/src/ext_backup_loader.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ext_backup_loader.h" - -#include "ext_backup.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -ExtBackupLoader::ExtBackupLoader() = default; -ExtBackupLoader::~ExtBackupLoader() = default; - -AbilityRuntime::Extension *ExtBackupLoader::Create(const unique_ptr &runtime) const -{ - HILOGI("Create as an BackupExtensionAbility(Loader)"); - return ExtBackup::Create(runtime); -} - -map ExtBackupLoader::GetParams() -{ - HILOGI("Register as an extension ability"); - return { - // Type 即为 Extension 类型,定义在 ExtensionAbilityType 这一枚举类中。具体位置见 extension_ability_info.h - {"type", "9"}, - {"name", "BackupExtensionAbility"}, - }; -} - -extern "C" __attribute__((visibility("default"))) void *OHOS_EXTENSION_GetExtensionModule() -{ - HILOGI("Load as a library"); - return &ExtBackupLoader::GetInstance(); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp deleted file mode 100644 index cae67913b..000000000 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ /dev/null @@ -1,512 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ext_extension.h" - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -#include "accesstoken_kit.h" -#include "b_error/b_error.h" -#include "b_filesystem/b_dir.h" -#include "b_filesystem/b_file.h" -#include "b_json/b_json_cached_entity.h" -#include "b_json/b_json_entity_ext_manage.h" -#include "b_resources/b_constants.h" -#include "b_tarball/b_tarball_factory.h" -#include "bundle_mgr_client.h" -#include "errors.h" -#include "filemgmt_libhilog.h" -#include "ipc_skeleton.h" -#include "service_proxy.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void BackupExtExtension::VerifyCaller() -{ - HILOGI("begin"); - uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); - int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); - if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { - throw BError(BError::Codes::EXT_BROKEN_IPC, - string("Calling tokenType is error, token type is ").append(to_string(tokenType))); - } - if (IPCSkeleton::GetCallingUid() != BConstants::BACKUP_UID) { - throw BError(BError::Codes::EXT_BROKEN_IPC, - string("Calling uid is invalid, calling uid is ").append(to_string(IPCSkeleton::GetCallingUid()))); - } -} - -UniqueFd BackupExtExtension::GetFileHandle(const string &fileName) -{ - if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { - HILOGI("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); - return UniqueFd(-1); - } - - VerifyCaller(); - - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { - stringstream ss; - ss << "Failed to create backup folder. "; - ss << std::generic_category().message(errno); - throw BError(BError::Codes::EXT_INVAL_ARG, ss.str()); - } - - string tarName = path + fileName; - return UniqueFd(open(tarName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); -} - -ErrCode BackupExtExtension::HandleClear() -{ - HILOGI("begin clear"); - try { - if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { - return EPERM; - } - VerifyCaller(); - - string backupCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); - string restoreCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - - if (!ForceRemoveDirectory(backupCache)) { - HILOGI("Failed to delete the backup cache %{public}s", backupCache.c_str()); - } - - if (!ForceRemoveDirectory(restoreCache)) { - HILOGI("Failed to delete the restore cache %{public}s", restoreCache.c_str()); - } - - tars_.clear(); - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGE(""); - return EPERM; - } - - return ERR_OK; -} - -ErrCode IndexFileReady(const map> &pkgInfo, sptr proxy) -{ - string indexFile = string(BConstants::PATH_BUNDLE_BACKUP_HOME). - append(BConstants::SA_BUNDLE_BACKUP_BACKUP). - append(BConstants::EXT_BACKUP_MANAGE); - BJsonCachedEntity cachedEntity( - UniqueFd(open(indexFile.data(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR))); - auto cache = cachedEntity.Structuralize(); - cache.SetExtManage(pkgInfo); - cachedEntity.Persist(); - close(cachedEntity.GetFd().Release()); - - ErrCode ret = - proxy->AppFileReady(string(BConstants::EXT_BACKUP_MANAGE), UniqueFd(open(indexFile.data(), O_RDONLY))); - if (SUCCEEDED(ret)) { - HILOGI("The application is packaged successfully"); - } else { - HILOGI( - "The application is packaged successfully but the AppFileReady interface fails to be invoked: " - "%{public}d", - ret); - } - return ret; -} - -ErrCode BigFileReady(sptr proxy) -{ - string indexFile = string(BConstants::PATH_BUNDLE_BACKUP_HOME). - append(BConstants::SA_BUNDLE_BACKUP_BACKUP). - append(BConstants::EXT_BACKUP_MANAGE); - BJsonCachedEntity cachedEntity(UniqueFd(open(indexFile.data(), O_RDONLY))); - auto cache = cachedEntity.Structuralize(); - map> pkgInfo = cache.GetExtManageInfo(); - - ErrCode ret {ERR_OK}; - for (auto &item : pkgInfo) { - if (item.first.empty() || item.second.first.empty()) { - continue; - } - - UniqueFd fd(open(item.second.first.data(), O_RDONLY)); - if (fd < 0) { - HILOGE("open file failed, file name is %{public}s", std::get<0>(item.second).c_str()); - continue; - } - - ret = proxy->AppFileReady(item.first, std::move(fd)); - if (SUCCEEDED(ret)) { - HILOGI("The application is packaged successfully, package name is %{public}s", item.first.c_str()); - } else { - HILOGI( - "The application is packaged successfully but the AppFileReady interface fails to be invoked: " - "%{public}d", - ret); - } - } - return ret; -} - -ErrCode BackupExtExtension::PublishFile(const string &fileName) -{ - HILOGI("begin publish file. fileName is %{public}s", fileName.data()); - try { - if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { - return BError(-EPERM); - } - VerifyCaller(); - - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - string tarName = path + fileName; - if (find(tars_.begin(), tars_.end(), fileName) != tars_.end() || access(tarName.data(), F_OK) != 0) { - return BError(-EPERM); - } - tars_.push_back(fileName); - - // 异步执行解压操作 - if (extension_->AllowToBackupRestore()) { - AsyncTaskRestore(); - } - - return ERR_OK; - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); - return BError(-EPERM); - } catch (...) { - HILOGE("Unexpected exception"); - return BError(-EPERM); - } -} - -ErrCode BackupExtExtension::HandleBackup() -{ - string usrConfig = extension_->GetUsrConfig(); - AsyncTaskBackup(usrConfig); - return 0; -} - -static map> GetBigFileInfo(const vector &includes, - const vector &excludes) -{ - auto [errCode, files] = BDir::GetBigFiles(includes, excludes); - if (errCode != 0) { - return {}; - } - - auto GetStringHash = [](const map> &m, const string &str) -> string { - ostringstream strHex; - strHex << hex; - - hash strHash; - size_t szHash = strHash(str); - strHex << setfill('0') << setw(BConstants::BIG_FILE_NAME_SIZE) << szHash; - string name = strHex.str(); - for (int i = 0; m.find(name) != m.end(); ++i, strHex.str("")) { - szHash = strHash(str + to_string(i)); - strHex << setfill('0') << setw(BConstants::BIG_FILE_NAME_SIZE) << szHash; - name = strHex.str(); - } - - return name; - }; - - map> bigFiles; - for (const auto &item : files) { - string md5Name = GetStringHash(bigFiles, item.first); - if (!md5Name.empty()) { - bigFiles.emplace(md5Name, make_pair(item.first, item.second)); - } - } - - return bigFiles; -} - -int BackupExtExtension::HandleBackup(const BJsonEntityExtensionConfig &usrConfig) -{ - HILOGI("Do backup"); - try { - if (extension_->GetExtensionAction() != BConstants::ExtensionAction::BACKUP) { - return EPERM; - } - - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); - if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { - throw BError(errno); - } - - vector includes = usrConfig.GetIncludes(); - vector excludes = usrConfig.GetExcludes(); - auto bigFileInfo = GetBigFileInfo(includes, excludes); - for (const auto &item : bigFileInfo) { - if (!item.second.first.empty()) { - excludes.push_back(item.second.first); - } - } - - string pkgName = "1.tar"; - string tarName = path + pkgName; - string root = "/"; - - // 打包 - auto tarballTar = BTarballFactory::Create("cmdline", tarName); - (tarballTar->tar)(root, {includes.begin(), includes.end()}, {excludes.begin(), excludes.end()}); - - struct stat sta = {}; - if (stat(tarName.data(), &sta) == -1) { - HILOGE("failed to invoke the system function stat, %{public}s", tarName.c_str()); - } - bigFileInfo.emplace(pkgName, make_pair(tarName, sta)); - - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); - } - - ErrCode ret = ERR_OK; - ret = IndexFileReady(bigFileInfo, proxy); - ret = BigFileReady(proxy); - return ret; - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGE(""); - return EPERM; - } -} - -int BackupExtExtension::HandleRestore(const string &fileName) -{ - HILOGI("Do restore"); - try { - if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { - return EPERM; - } - // REM: 给定version - // REM: 解压启动Extension时即挂载好的备份目录中的数据 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - string tarName = path + fileName; - - auto tarballFunc = BTarballFactory::Create("cmdline", tarName); - (tarballFunc->untar)("/"); - HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); - - return ERR_OK; - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGE(""); - return EPERM; - } -} - -void BackupExtExtension::AsyncTaskBackup(const string config) -{ - auto task = [obj {wptr(this)}, config]() { - auto ptr = obj.promote(); - if (!ptr) { - HILOGI("ext_extension handle have been already released"); - return; - } - - BJsonCachedEntity cachedEntity(config); - auto cache = cachedEntity.Structuralize(); - if (!cache.GetAllowToBackupRestore()) { - HILOGI("Application does not allow backup or restore"); - return; - } - - int ret = ptr->HandleBackup(cache); - - // REM: 处理返回结果 ret - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - HILOGE("Failed to obtain the ServiceProxy handle"); - return; - } else { - proxy->AppDone(ret); - } - - // 清空备份目录 - ptr->HandleClear(); - }; - - // REM: 这里异步化了,需要做并发控制 - // 在往线程池中投入任务之前将需要的数据拷贝副本到参数中,保证不发生读写竞争, - // 由于拷贝参数时尚运行在主线程中,故在参数拷贝过程中是线程安全的。 - threadPool_.AddTask([task]() { - try { - task(); - } catch (const BError &e) { - HILOGE("%{public}s", e.what()); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - } catch (...) { - HILOGE(""); - } - }); -} - -static bool IsAllFileReceived(vector tars) -{ - // 是否已收到索引文件 - auto it = find(tars.begin(), tars.end(), string(BConstants::EXT_BACKUP_MANAGE)); - if (tars.end() == it) { - return false; - } - - // 获取索引文件内容 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - string indexFile = path + string(BConstants::EXT_BACKUP_MANAGE); - BJsonCachedEntity cachedEntity(UniqueFd(open(indexFile.data(), O_RDONLY))); - auto cache = cachedEntity.Structuralize(); - set info = cache.GetExtManage(); - - // 从数量上判断是否已经全部收到 - if (tars.size() <= info.size()) { - return false; - } - - // 逐个判断是否收到 - sort(tars.begin(), tars.end()); - if (includes(tars.begin(), tars.end(), info.begin(), info.end())) { - return true; - } - return false; -} - -static void RestoreBigFiles() -{ - // 获取索引文件内容 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - string indexFile = path + string(BConstants::EXT_BACKUP_MANAGE); - BJsonCachedEntity cachedEntity(UniqueFd(open(indexFile.data(), O_RDONLY))); - auto cache = cachedEntity.Structuralize(); - auto info = cache.GetExtManageInfo(); - - for (auto &item : info) { - if (item.first.empty() || item.first.size() < BConstants::BIG_FILE_NAME_SIZE || - item.first.rfind('.') != string::npos) { - continue; - } - - string fileName = path + item.first; - auto [filePath, sta] = item.second; - - if (access(fileName.data(), F_OK) != 0) { - HILOGI("file dose not exist"); - continue; - } - if (filePath.empty()) { - HILOGE("file path is empty. %{public}s", filePath.c_str()); - continue; - } - if (rename(fileName.data(), filePath.data()) != 0) { - HILOGE("failed to rename the file, try to copy it. err = %{public}d", errno); - if (!BFile::CopyFile(fileName, filePath)) { - HILOGE("failed to copy the file. err = %{public}d", errno); - continue; - } - HILOGI("succeed to rename or copy the file"); - } - set lks = cache.GetHardLinkInfo(item.first); - for (const auto &lksPath : lks) { - if (link(filePath.data(), lksPath.data())) { - HILOGE("failed to create hard link file %{public}s errno : %{public}d", lksPath.c_str(), errno); - } - } - - struct timespec tv[2] = {sta.st_atim, sta.st_mtim}; - UniqueFd fd(open(filePath.data(), O_RDONLY)); - if (futimens(fd.Get(), tv) != 0) { - HILOGI("failed to change the file time. %{public}s , %{public}d", filePath.c_str(), errno); - } - } -} - -void BackupExtExtension::AsyncTaskRestore() -{ - auto task = [obj {wptr(this)}, tars {tars_}]() { - auto ptr = obj.promote(); - if (!ptr) { - HILOGI("ext_extension handle have been already released"); - return; - } - - if (!IsAllFileReceived(tars)) { - return; - } - - // 解压 - int ret = ERR_OK; - for (auto item : tars) { - if (ExtractFileExt(item) == "tar") { - ret = ptr->HandleRestore(item); - } - } - // 恢复大文件 - RestoreBigFiles(); - - // 处理返回结果 - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - HILOGE("Failed to obtain the ServiceProxy handle"); - return; - } else { - proxy->AppDone(ret); - } - - // 清空恢复目录 - ptr->HandleClear(); - }; - - // REM: 这里异步化了,需要做并发控制 - // 在往线程池中投入任务之前将需要的数据拷贝副本到参数中,保证不发生读写竞争, - // 由于拷贝参数时尚运行在主线程中,故在参数拷贝过程中是线程安全的。 - threadPool_.AddTask([task]() { - try { - task(); - } catch (const BError &e) { - HILOGE("%{public}s", e.what()); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - } catch (...) { - HILOGE(""); - } - }); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/ext_extension_stub.cpp b/frameworks/native/backup_ext/src/ext_extension_stub.cpp deleted file mode 100644 index b47515b07..000000000 --- a/frameworks/native/backup_ext/src/ext_extension_stub.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "ext_extension_stub.h" - -#include -#include - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -ExtExtensionStub::ExtExtensionStub() -{ - opToInterfaceMap_[CMD_GET_FILE_HANDLE] = &ExtExtensionStub::CmdGetFileHandle; - opToInterfaceMap_[CMD_HANDLE_CLAER] = &ExtExtensionStub::CmdHandleClear; - opToInterfaceMap_[CMD_HANDLE_BACKUP] = &ExtExtensionStub::CmdHandleBackup; - opToInterfaceMap_[CMD_PUBLISH_FILE] = &ExtExtensionStub::CmdPublishFile; -} - -int32_t ExtExtensionStub::OnRemoteRequest(uint32_t code, - MessageParcel &data, - MessageParcel &reply, - MessageOption &option) -{ - HILOGI("Begin to call procedure indexed %{public}u", code); - auto interfaceIndex = opToInterfaceMap_.find(code); - if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { - stringstream ss; - ss << "Cannot response request " << code << ": unknown procedure"; - return BError(BError::Codes::EXT_INVAL_ARG, ss.str()); - } - - const std::u16string descriptor = ExtExtensionStub::GetDescriptor(); - const std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - return BError(BError::Codes::EXT_INVAL_ARG, "Invalid remote descriptor"); - } - - return BError::ExceptionCatcherLocked([&]() { return ErrCode((this->*(interfaceIndex->second))(data, reply)); }); -} - -ErrCode ExtExtensionStub::CmdGetFileHandle(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - string fileName; - if (!data.ReadString(fileName)) { - return BError(BError::Codes::EXT_INVAL_ARG, "Failed to receive fileName").GetCode(); - } - - UniqueFd fd = GetFileHandle(fileName); - if (!reply.WriteFileDescriptor(fd)) { - return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the file").GetCode(); - } - return BError(BError::Codes::OK); -} - -ErrCode ExtExtensionStub::CmdHandleClear(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - ErrCode res = HandleClear(); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::EXT_BROKEN_IPC, ss.str()).GetCode(); - } - return BError(BError::Codes::OK); -} - -ErrCode ExtExtensionStub::CmdHandleBackup(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - ErrCode res = HandleBackup(); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::EXT_BROKEN_IPC, ss.str()).GetCode(); - } - return BError(BError::Codes::OK); -} - -ErrCode ExtExtensionStub::CmdPublishFile(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - string fileName; - if (!data.ReadString(fileName)) { - return BError(BError::Codes::EXT_INVAL_ARG, "Failed to receive fileName"); - } - - ErrCode res = PublishFile(fileName); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::EXT_BROKEN_IPC, ss.str()).GetCode(); - } - return BError(BError::Codes::OK); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/include/service_reverse.h b/frameworks/native/backup_kit_inner/include/service_reverse.h deleted file mode 100644 index f0810e14a..000000000 --- a/frameworks/native/backup_kit_inner/include/service_reverse.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_H -#define OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_H - -#include "b_session_backup.h" -#include "b_session_restore.h" -#include "service_reverse_stub.h" - -namespace OHOS::FileManagement::Backup { -class ServiceReverse final : public ServiceReverseStub { -public: - void BackupOnFileReady(std::string bundleName, std::string fileName, int fd) override; - void BackupOnBundleStarted(int32_t errCode, std::string bundleName) override; - void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; - void BackupOnAllBundlesFinished(int32_t errCode) override; - - void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; - void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; - void RestoreOnAllBundlesFinished(int32_t errCode) override; - void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) override; - -public: - ServiceReverse() = delete; - explicit ServiceReverse(BSessionRestore::Callbacks callbacks); - explicit ServiceReverse(BSessionBackup::Callbacks callbacks); - ~ServiceReverse() override = default; - -private: - Scenario scenario_ {Scenario::UNDEFINED}; - BSessionBackup::Callbacks callbacksBackup_; - BSessionRestore::Callbacks callbacksRestore_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_H \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h deleted file mode 100644 index 5c46907b2..000000000 --- a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_STUB_H -#define OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_STUB_H - -#include - -#include "i_service_reverse.h" -#include "iremote_stub.h" - -namespace OHOS::FileManagement::Backup { -class ServiceReverseStub : public IRemoteStub { -public: - int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - -public: - ServiceReverseStub(); - ~ServiceReverseStub() override = default; - -private: - using ServiceInterface = int32_t (ServiceReverseStub::*)(MessageParcel &data, MessageParcel &reply); - std::map opToInterfaceMap_; - - int32_t CmdBackupOnFileReady(MessageParcel &data, MessageParcel &reply); - int32_t CmdBackupOnBundleStarted(MessageParcel &data, MessageParcel &reply); - int32_t CmdBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); - int32_t CmdBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); - - int32_t CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); - int32_t CmdRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); - int32_t CmdRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); - int32_t CmdRestoreOnFileReady(MessageParcel &data, MessageParcel &reply); -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_STUB_H diff --git a/frameworks/native/backup_kit_inner/src/b_file_info.cpp b/frameworks/native/backup_kit_inner/src/b_file_info.cpp deleted file mode 100644 index e068da158..000000000 --- a/frameworks/native/backup_kit_inner/src/b_file_info.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_file_info.h" - -#include "filemgmt_libhilog.h" - -namespace OHOS { -namespace FileManagement { -namespace Backup { -using namespace std; - -bool BFileInfo::Marshalling(Parcel &parcel) const -{ - if (!parcel.WriteString(owner) || !parcel.WriteString(fileName) || !parcel.WriteUint32(sn)) { - HILOGE("Failed"); - return false; - } - return true; -} - -bool BFileInfo::ReadFromParcel(Parcel &parcel) -{ - if (!parcel.ReadString(owner) || !parcel.ReadString(fileName) || !parcel.ReadUint32(sn)) { - HILOGE("Failed"); - return false; - } - return true; -} - -BFileInfo *BFileInfo::Unmarshalling(Parcel &parcel) -{ - try { - auto result = make_unique(); - if (!result->ReadFromParcel(parcel)) { - return nullptr; - } - return result.release(); - } catch (const bad_alloc &e) { - HILOGE("Failed to unmarshall BFileInfo because of %{public}s", e.what()); - } - return nullptr; -} -} // namespace Backup -} // namespace FileManagement -} // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp deleted file mode 100644 index 7da9c9716..000000000 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_session_backup.h" - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" -#include "service_proxy.h" -#include "service_reverse.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -BSessionBackup::~BSessionBackup() -{ - if (!deathRecipient_) { - HILOGI("Death Recipient is nullptr"); - return; - } - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - return; - } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; -} - -unique_ptr BSessionBackup::Init(UniqueFd remoteCap, - vector bundlesToBackup, - Callbacks callbacks) -{ - try { - auto backup = make_unique(); - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - HILOGI("Failed to get backup service"); - return nullptr; - } - - int32_t res = proxy->InitBackupSession(sptr(new ServiceReverse(callbacks)), move(remoteCap), bundlesToBackup); - if (res != 0) { - HILOGE("Failed to Backup because of %{public}d", res); - return nullptr; - } - - backup->RegisterBackupServiceDied(callbacks.onBackupServiceDied); - return backup; - } catch (const exception &e) { - HILOGE("Failed to Backup because of %{public}s", e.what()); - } - return nullptr; -} - -void BSessionBackup::RegisterBackupServiceDied(std::function functor) -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr || !functor) { - return; - } - auto remoteObj = proxy->AsObject(); - if (!remoteObj) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Proxy's remote object can't be nullptr"); - } - - auto callback = [functor](const wptr &obj) { - HILOGI("Backup service died"); - functor(); - }; - deathRecipient_ = sptr(new SvcDeathRecipient(callback)); - remoteObj->AddDeathRecipient(deathRecipient_); -} - -ErrCode BSessionBackup::Start() -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); - } - - return proxy->Start(); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp deleted file mode 100644 index 34ef872a5..000000000 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_session_restore.h" - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" -#include "service_proxy.h" -#include "service_reverse.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -BSessionRestore::~BSessionRestore() -{ - if (!deathRecipient_) { - HILOGI("Death Recipient is nullptr"); - return; - } - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - return; - } - auto remoteObject = proxy->AsObject(); - if (remoteObject != nullptr) { - remoteObject->RemoveDeathRecipient(deathRecipient_); - } - deathRecipient_ = nullptr; -} - -unique_ptr BSessionRestore::Init(std::vector bundlesToRestore, Callbacks callbacks) -{ - try { - auto restore = make_unique(); - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - HILOGI("Failed to get backup service"); - return nullptr; - } - int32_t res = proxy->InitRestoreSession(new ServiceReverse(callbacks), bundlesToRestore); - if (res != 0) { - HILOGE("Failed to Restore because of %{public}d", res); - return nullptr; - } - - restore->RegisterBackupServiceDied(callbacks.onBackupServiceDied); - return restore; - } catch (const exception &e) { - HILOGE("Failed to Restore because of %{public}s", e.what()); - } - return nullptr; -} - -UniqueFd BSessionRestore::GetLocalCapabilities() -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - HILOGI("Failed to proxy because of is empty"); - return UniqueFd(-1); - } - return UniqueFd(proxy->GetLocalCapabilities()); -} - -ErrCode BSessionRestore::PublishFile(BFileInfo fileInfo) -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); - } - return proxy->PublishFile(fileInfo); -} - -ErrCode BSessionRestore::Start() -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); - } - - return proxy->Start(); -} - -ErrCode BSessionRestore::GetExtFileName(string &bundleName, string &fileName) -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); - } - - return proxy->GetExtFileName(bundleName, fileName); -} - -void BSessionRestore::RegisterBackupServiceDied(std::function functor) -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr || !functor) { - return; - } - auto remoteObj = proxy->AsObject(); - if (!remoteObj) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Proxy's remote object can't be nullptr"); - } - - auto callback = [functor](const wptr &obj) { - HILOGI("Backup service died"); - functor(); - }; - deathRecipient_ = sptr(new SvcDeathRecipient(callback)); - remoteObj->AddDeathRecipient(deathRecipient_); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp deleted file mode 100644 index 1bc9826b1..000000000 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "service_proxy.h" - -#include -#include - -#include "b_error/b_error.h" -#include "b_resources/b_constants.h" -#include "filemgmt_libhilog.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -int32_t ServiceProxy::InitRestoreSession(sptr remote, const std::vector &bundleNames) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - MessageParcel reply; - MessageOption option; - - if (!remote) { - return BError(BError::Codes::SDK_INVAL_ARG, "Empty reverse stub").GetCode(); - } - if (!data.WriteRemoteObject(remote->AsObject().GetRefPtr())) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the reverse stub").GetCode(); - } - - if (!data.WriteStringVector(bundleNames)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleNames").GetCode(); - } - - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_INIT_RESTORE_SESSION, data, reply, option); - if (ret != NO_ERROR) { - stringstream ss; - ss << "Failed to send out the request for " << ret; - return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); - } - HILOGI("Successful"); - return reply.ReadInt32(); -} - -int32_t ServiceProxy::InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - MessageParcel reply; - MessageOption option; - - if (!remote) { - return BError(BError::Codes::SDK_INVAL_ARG, "Empty reverse stub").GetCode(); - } - if (!data.WriteRemoteObject(remote->AsObject().GetRefPtr())) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the reverse stub").GetCode(); - } - - if (!data.WriteFileDescriptor(fd)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fd").GetCode(); - } - if (!data.WriteStringVector(bundleNames)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleNames").GetCode(); - } - - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_INIT_BACKUP_SESSION, data, reply, option); - if (ret != NO_ERROR) { - stringstream ss; - ss << "Failed to send out the request because of " << ret; - return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); - } - HILOGI("Successful"); - return reply.ReadInt32(); -} - -ErrCode ServiceProxy::Start() -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_START, data, reply, option); - if (ret != NO_ERROR) { - stringstream ss; - ss << "Failed to send out the request because of " << ret; - return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); - } - - HILOGI("Successful"); - return reply.ReadInt32(); -} - -UniqueFd ServiceProxy::GetLocalCapabilities() -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_GET_LOCAL_CAPABILITIES, data, reply, option); - if (ret != NO_ERROR) { - HILOGE("Received error %{public}d when doing IPC", ret); - return UniqueFd(-ret); - } - - HILOGI("Successful"); - UniqueFd fd(reply.ReadFileDescriptor()); - return UniqueFd(fd.Release()); -} - -ErrCode ServiceProxy::PublishFile(const BFileInfo &fileInfo) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - if (!data.WriteParcelable(&fileInfo)) { - HILOGE("Failed to send the fileInfo"); - return -EPIPE; - } - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_PUBLISH_FILE, data, reply, option); - if (ret != NO_ERROR) { - stringstream ss; - ss << "Failed to send out the request because of " << ret; - return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); - } - - HILOGI("Successful"); - return reply.ReadInt32(); -} - -ErrCode ServiceProxy::AppFileReady(const string &fileName, UniqueFd fd) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - if (!data.WriteString(fileName)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the filename").GetCode(); - } - if (!data.WriteFileDescriptor(fd)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fd").GetCode(); - } - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_APP_FILE_READY, data, reply, option); - if (ret != NO_ERROR) { - stringstream ss; - ss << "Failed to send out the request because of " << ret; - return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); - } - HILOGI("Successful"); - return reply.ReadInt32(); -} - -ErrCode ServiceProxy::AppDone(ErrCode errCode) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - if (!data.WriteInt32(errCode)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the errCode").GetCode(); - } - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_APP_DONE, data, reply, option); - if (ret != NO_ERROR) { - stringstream ss; - ss << "Failed to send out the request because of " << ret; - return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); - } - HILOGI("Successful"); - return reply.ReadInt32(); -} - -ErrCode ServiceProxy::GetExtFileName(string &bundleName, string &fileName) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - if (!data.WriteString(bundleName)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the bundleName").GetCode(); - } - if (!data.WriteString(fileName)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fileName").GetCode(); - } - - MessageParcel reply; - MessageOption option; - option.SetFlags(MessageOption::TF_ASYNC); - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_GET_EXT_FILE_NAME, data, reply, option); - if (ret != NO_ERROR) { - stringstream ss; - ss << "Failed to send out the request because of " << ret; - BError(BError::Codes::SDK_INVAL_ARG, ss.str()); - } - HILOGI("Successful"); - return ret; -} - -sptr ServiceProxy::GetInstance() -{ - unique_lock lock(proxyMutex_); - if (serviceProxy_ != nullptr) { - return serviceProxy_; - } - - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (!samgr) { - HILOGE("Get an empty samgr"); - return nullptr; - } - sptr loadCallback = new ServiceProxyLoadCallback(); - if (loadCallback == nullptr) { - HILOGE("loadCallback is nullptr."); - return nullptr; - } - int32_t ret = samgr->LoadSystemAbility(FILEMANAGEMENT_BACKUP_SERVICE_SA_ID, loadCallback); - if (ret != ERR_OK) { - HILOGE("Failed to Load systemAbility, systemAbilityId:%d, ret code:%d", FILEMANAGEMENT_BACKUP_SERVICE_SA_ID, - ret); - return nullptr; - } - - auto waitStatus = - loadCallback->proxyConVar_.wait_for(lock, std::chrono::milliseconds(BConstants::BACKUP_LOADSA_TIMEOUT_MS), - [loadCallback]() { return loadCallback->isLoadSuccess_.load(); }); - if (!waitStatus) { - HILOGE("Load backup sa timeout"); - return nullptr; - } - return serviceProxy_; -} - -void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, - const OHOS::sptr &remoteObject) -{ - HILOGI("Load backup sa success, systemAbilityId:%d, remoteObject result:%s", systemAbilityId, - (remoteObject != nullptr) ? "true" : "false"); - unique_lock lock(proxyMutex_); - serviceProxy_ = iface_cast(remoteObject); - isLoadSuccess_.store(true); - proxyConVar_.notify_one(); -} - -void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) -{ - HILOGE("Load backup sa failed, systemAbilityId:%d", systemAbilityId); - unique_lock lock(proxyMutex_); - serviceProxy_ = nullptr; - isLoadSuccess_.store(false); - proxyConVar_.notify_one(); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/service_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_reverse.cpp deleted file mode 100644 index 78b73f09b..000000000 --- a/frameworks/native/backup_kit_inner/src/service_reverse.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "service_reverse.h" - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void ServiceReverse::BackupOnFileReady(string bundleName, string fileName, int fd) -{ - HILOGI("begin"); - if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onFileReady) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - BFileInfo bFileInfo(bundleName, fileName, 0); - callbacksBackup_.onFileReady(bFileInfo, UniqueFd(fd)); -} - -void ServiceReverse::BackupOnBundleStarted(int32_t errCode, string bundleName) -{ - HILOGI("begin"); - if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onBundleStarted) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - callbacksBackup_.onBundleStarted(errCode, bundleName); -} - -void ServiceReverse::BackupOnBundleFinished(int32_t errCode, string bundleName) -{ - HILOGI("begin"); - if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - callbacksBackup_.onBundleFinished(errCode, bundleName); -} - -void ServiceReverse::BackupOnAllBundlesFinished(int32_t errCode) -{ - HILOGI("errCode = %{public}d", errCode); - if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onAllBundlesFinished) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - callbacksBackup_.onAllBundlesFinished(errCode); -} - -void ServiceReverse::RestoreOnBundleStarted(int32_t errCode, string bundleName) -{ - HILOGI("begin"); - if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleStarted) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - callbacksRestore_.onBundleStarted(errCode, bundleName); -} - -void ServiceReverse::RestoreOnBundleFinished(int32_t errCode, string bundleName) -{ - HILOGI("begin"); - if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - callbacksRestore_.onBundleFinished(errCode, bundleName); -} - -void ServiceReverse::RestoreOnAllBundlesFinished(int32_t errCode) -{ - HILOGI("errCode = %{public}d", errCode); - if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onAllBundlesFinished) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - callbacksRestore_.onAllBundlesFinished(errCode); -} - -void ServiceReverse::RestoreOnFileReady(string bundleName, string fileName, int fd) -{ - HILOGI("begin"); - if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onFileReady) { - HILOGI("Error scenario or callback is nullptr"); - return; - } - BFileInfo bFileInfo(bundleName, fileName, 0); - callbacksRestore_.onFileReady(bFileInfo, UniqueFd(fd)); -} - -ServiceReverse::ServiceReverse(BSessionBackup::Callbacks callbacks) - : scenario_(Scenario::BACKUP), callbacksBackup_(callbacks) -{ -} - -ServiceReverse::ServiceReverse(BSessionRestore::Callbacks callbacks) - : scenario_(Scenario::RESTORE), callbacksRestore_(callbacks) -{ -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp deleted file mode 100644 index 9445a28de..000000000 --- a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "service_reverse_stub.h" - -#include -#include - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -int32_t ServiceReverseStub::OnRemoteRequest(uint32_t code, - MessageParcel &data, - MessageParcel &reply, - MessageOption &option) -{ - HILOGI("Begin to call procedure indexed %{public}u", code); - auto interfaceIndex = opToInterfaceMap_.find(code); - if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { - stringstream ss; - ss << "Cannot response request " << code << ": unknown procedure"; - return BError(BError::Codes::SA_INVAL_ARG, ss.str()); - } - - const std::u16string descriptor = ServiceReverseStub::GetDescriptor(); - const std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - return BError(BError::Codes::SA_INVAL_ARG, "Invalid remote descriptor"); - } - - return (this->*(interfaceIndex->second))(data, reply); -} - -ServiceReverseStub::ServiceReverseStub() -{ - opToInterfaceMap_[SERVICER_BACKUP_ON_FILE_READY] = &ServiceReverseStub::CmdBackupOnFileReady; - opToInterfaceMap_[SERVICER_BACKUP_ON_SUB_TASK_STARTED] = &ServiceReverseStub::CmdBackupOnBundleStarted; - opToInterfaceMap_[SERVICER_BACKUP_ON_SUB_TASK_FINISHED] = &ServiceReverseStub::CmdBackupOnBundleFinished; - opToInterfaceMap_[SERVICER_BACKUP_ON_TASK_FINISHED] = &ServiceReverseStub::CmdBackupOnAllBundlesFinished; - - opToInterfaceMap_[SERVICER_RESTORE_ON_SUB_TASK_STARTED] = &ServiceReverseStub::CmdRestoreOnBundleStarted; - opToInterfaceMap_[SERVICER_RESTORE_ON_SUB_TASK_FINISHED] = &ServiceReverseStub::CmdRestoreOnBundleFinished; - opToInterfaceMap_[SERVICER_RESTORE_ON_TASK_FINISHED] = &ServiceReverseStub::CmdRestoreOnAllBundlesFinished; - opToInterfaceMap_[SERVICER_RESTORE_ON_FILE_READY] = &ServiceReverseStub::CmdRestoreOnFileReady; -} - -int32_t ServiceReverseStub::CmdBackupOnFileReady(MessageParcel &data, MessageParcel &reply) -{ - auto bundleName = data.ReadString(); - auto fileName = data.ReadString(); - int fd = data.ReadFileDescriptor(); - BackupOnFileReady(bundleName, fileName, fd); - return BError(BError::Codes::OK); -} - -int32_t ServiceReverseStub::CmdBackupOnBundleStarted(MessageParcel &data, MessageParcel &reply) -{ - int32_t errCode = data.ReadInt32(); - auto bundleName = data.ReadString(); - BackupOnBundleStarted(errCode, bundleName); - return BError(BError::Codes::OK); -} - -int32_t ServiceReverseStub::CmdBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply) -{ - int32_t errCode = data.ReadInt32(); - auto bundleName = data.ReadString(); - BackupOnBundleFinished(errCode, bundleName); - return BError(BError::Codes::OK); -} - -int32_t ServiceReverseStub::CmdBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply) -{ - int32_t errCode = data.ReadInt32(); - BackupOnAllBundlesFinished(errCode); - return BError(BError::Codes::OK); -} - -int32_t ServiceReverseStub::CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) -{ - int32_t errCode = data.ReadInt32(); - auto bundleName = data.ReadString(); - RestoreOnBundleStarted(errCode, bundleName); - return BError(BError::Codes::OK); -} - -int32_t ServiceReverseStub::CmdRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply) -{ - int32_t errCode = data.ReadInt32(); - auto bundleName = data.ReadString(); - RestoreOnBundleFinished(errCode, bundleName); - return BError(BError::Codes::OK); -} - -int32_t ServiceReverseStub::CmdRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply) -{ - int32_t errCode = data.ReadInt32(); - RestoreOnAllBundlesFinished(errCode); - return BError(BError::Codes::OK); -} - -int32_t ServiceReverseStub::CmdRestoreOnFileReady(MessageParcel &data, MessageParcel &reply) -{ - auto bundleName = data.ReadString(); - auto fileName = data.ReadString(); - int fd = data.ReadFileDescriptor(); - RestoreOnFileReady(bundleName, fileName, fd); - return BError(BError::Codes::OK); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/interfaces/api/js/napi/backup_ext/BUILD.gn b/interfaces/api/js/napi/backup_ext/BUILD.gn deleted file mode 100644 index 51072aae4..000000000 --- a/interfaces/api/js/napi/backup_ext/BUILD.gn +++ /dev/null @@ -1,52 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni") -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ts2abc_gen_abc("gen_backup_extension_ability_abc") { - src_js = rebase_path("backup_extension_ability.js") - dst_file = rebase_path(target_out_dir + "/backup_extension_ability.abc") - in_puts = [ "backup_extension_ability.js" ] - out_puts = [ target_out_dir + "/backup_extension_ability.abc" ] - extra_args = [ "--module" ] -} - -gen_js_obj("backup_extension_ability_js") { - input = "backup_extension_ability.js" - output = target_out_dir + "/backup_extension_ability.o" -} - -gen_js_obj("backup_extension_ability_abc") { - input = get_label_info(":gen_backup_extension_ability_abc", - "target_out_dir") + "/backup_extension_ability.abc" - output = target_out_dir + "/backup_extension_ability_abc.o" - dep = ":gen_backup_extension_ability_abc" -} - -# 必须命名为backupextensionability或backupextensionability_napi -# 在将@ohos.application.BackupExtensionAblity翻译为库名时,只是将.作为目录分割符,然后将库名转换为小写后拼接.z.so或_napi.z.so后进行查找 -# 即,尝试加载/system/lib64/application/backupextensionability.z.so或/system//lib64/application/backupextensionability_napi.z.so -# 具体请参考//foundation/arkui/napi/module_manager/native_module_manager.cpp -ohos_shared_library("backupextensionability_napi") { - deps = [ - ":backup_extension_ability_abc", - ":backup_extension_ability_js", - "${path_backup}/frameworks/js/backup_ext:backupextensionability_napi_fwk", - ] - - relative_install_dir = "module/application" - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/interfaces/api/js/napi/backup_ext/backup_extension_ability.js b/interfaces/api/js/napi/backup_ext/backup_extension_ability.js deleted file mode 100644 index 1e21a35d2..000000000 --- a/interfaces/api/js/napi/backup_ext/backup_extension_ability.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -class BackupExtensionAbility { - onBackup() { - console.log() - } - - onRestore(versionBackupedBundle) { - console.log(versionBackupedBundle) - } -} - -export default BackupExtensionAbility \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn b/interfaces/inner_api/native/backup_kit_inner/BUILD.gn deleted file mode 100644 index 84634a4e5..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//build/ohos_var.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -config("public_config") { - include_dirs = [ - ".", - "impl", - ] -} - -config("private_config") { - include_dirs = [ - "${path_backup}/frameworks/native/backup_kit_inner/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - ] -} - -ohos_shared_library("backup_kit_inner") { - sources = [ - "${path_backup}/frameworks/native/backup_kit_inner/src/b_file_info.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_backup.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_restore.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/service_proxy.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", - ] - - defines = [ - "LOG_DOMAIN=0xD004302", - "LOG_TAG=\"BackupAPI\"", - ] - - configs = [ ":private_config" ] - public_configs = [ ":public_config" ] - - external_deps = [ - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - - public_deps = [ - "${path_backup}/utils:backup_utils", - "${path_base}:utils", - "${path_ipc}/interfaces/innerkits/ipc_core:ipc_core", - ] - - use_exceptions = true - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h b/interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h deleted file mode 100644 index b00355627..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_BACKUP_KIT_INNER_H -#define OHOS_FILEMGMT_BACKUP_BACKUP_KIT_INNER_H - -#include "impl/b_session_backup.h" -#include "impl/b_session_restore.h" - -#endif // OHOS_FILEMGMT_BACKUP_BACKUP_KIT_INNER_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_file_info.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_file_info.h deleted file mode 100644 index 356ad5226..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_file_info.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_FILE_INFO_H -#define OHOS_FILEMGMT_BACKUP_B_FILE_INFO_H - -#include -#include - -#include "parcel.h" - -namespace OHOS::FileManagement::Backup { -using BundleName = std::string; -using TmpFileSN = uint32_t; - -struct BFileInfo : public Parcelable { - BundleName owner; - std::string fileName; - TmpFileSN sn; // 用于服务零拷贝接收文件场景 - - BFileInfo() = default; - BFileInfo(std::string bundleName, std::string strFileNanme, TmpFileSN id) - : owner(bundleName), fileName(strFileNanme), sn(id) {} - ~BFileInfo() override = default; - - bool ReadFromParcel(Parcel &parcel); - bool Marshalling(Parcel &parcel) const override; - static BFileInfo *Unmarshalling(Parcel &parcel); -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_FILE_INFO_H diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h deleted file mode 100644 index d5e40d47d..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_SESSION_BACKUP_H -#define OHOS_FILEMGMT_BACKUP_B_SESSION_BACKUP_H - -#include -#include -#include - -#include "b_file_info.h" -#include "errors.h" -#include "svc_death_recipient.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -class BSessionBackup { -public: - struct Callbacks { - std::function onFileReady; // 当备份服务有文件待发送时执行的回调 - std::function onBundleStarted; // 当启动某个应用的备份流程结束时执行的回调函数 - std::function onBundleFinished; // 当某个应用的备份流程结束或意外中止时执行的回调函数 - std::function onAllBundlesFinished; // 当整个备份流程结束或意外中止时执行的回调函数 - std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 - }; - -public: - /** - * @brief 获取一个用于控制备份流程的会话 - * - * @param remoteCap 已打开的保存远端设备能力的Json文件。可使用BRestoreSession的GetLocalCapabilities方法获取 - * @param bundlesToBackup 待备份应用清单 - * @return std::unique_ptr 指向会话的智能指针。失败时为空指针 - */ - static std::unique_ptr Init(UniqueFd remoteCap, - std::vector bundlesToBackup, - Callbacks callbacks); - - /** - * @brief 用于启动备份流程 - * - * @return ErrCode 规范错误码 - */ - ErrCode Start(); - - /** - * @brief 注册备份服务意外死亡时执行的回调函数 - * - * @param functor 回调函数 - */ - void RegisterBackupServiceDied(std::function functor); - -public: - ~BSessionBackup(); - -private: - sptr deathRecipient_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_SESSION_BACKUP_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h deleted file mode 100644 index 33b38274e..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_SESSION_RESTORE_H -#define OHOS_FILEMGMT_BACKUP_B_SESSION_RESTORE_H - -#include -#include -#include - -#include "b_file_info.h" -#include "errors.h" -#include "svc_death_recipient.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -class BSessionRestore { -public: - struct Callbacks { - std::function onFileReady; // 当备份服务有文件待发送时执行的回调 - std::function onBundleStarted; // 当启动某个应用的恢复流程结束时执行的回调函数 - std::function onBundleFinished; // 当某个应用的恢复流程结束或意外中止时执行的回调函数 - std::function onAllBundlesFinished; // 当整个恢复流程结束或意外中止时执行的回调函数 - std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 - }; - -public: - /** - * @brief 获取一个用于控制恢复流程的会话 - * - * @param bundlesToRestore 待恢复应用清单 - * @param callbacks 注册的回调函数 - * @return std::unique_ptr 指向BRestoreSession的智能指针。失败时为空指针 - */ - static std::unique_ptr Init(std::vector bundlesToRestore, Callbacks callbacks); - - /** - * @brief 获取用于描述本端能力的Json文件 - * - * @return UniqueFd 文件描述符 - */ - UniqueFd GetLocalCapabilities(); - - /** - * @brief 通知备份服务文件内容已就绪 - * - * @param fileInfo 文件描述信息 - * @return ErrCode 规范错误码 - * @see GetExtFileName - */ - ErrCode PublishFile(BFileInfo fileInfo); - - /** - * @brief 请求恢复流程所需的真实文件 - * - * @param bundleName 应用名称 - * @param fileName 文件名称 - */ - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName); - - /** - * @brief 用于启动恢复流程 - * - * @return ErrCode 规范错误码 - */ - ErrCode Start(); - - /** - * @brief 注册备份服务意外死亡时执行的回调函数 - * - * @param functor 回调函数 - */ - void RegisterBackupServiceDied(std::function functor); - -public: - ~BSessionRestore(); - -private: - sptr deathRecipient_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_SESSION_RESTORE_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h deleted file mode 100644 index 9355df314..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_I_EXTENSION_H -#define OHOS_FILEMGMT_BACKUP_I_EXTENSION_H - -#include - -#include "errors.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -class IExtension : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileManagement.Backup.IExtension"); - - enum { - CMD_GET_FILE_HANDLE = 1, - CMD_HANDLE_CLAER, - CMD_PUBLISH_FILE, - CMD_HANDLE_BACKUP, - }; - -public: - virtual UniqueFd GetFileHandle(const std::string &fileName) = 0; - virtual ErrCode HandleClear() = 0; - virtual ErrCode HandleBackup() = 0; - virtual ErrCode PublishFile(const std::string &fileName) = 0; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_I_EXTENSION_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h deleted file mode 100644 index bc240c71b..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_I_SERVICE_H -#define OHOS_FILEMGMT_BACKUP_I_SERVICE_H - -#include -#include - -#include "b_file_info.h" -#include "i_service_reverse.h" -#include "iremote_broker.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -class IService : public IRemoteBroker { -public: - enum { - SERVICE_CMD_INIT_RESTORE_SESSION, - SERVICE_CMD_INIT_BACKUP_SESSION, - SERVICE_CMD_GET_LOCAL_CAPABILITIES, - SERVICE_CMD_PUBLISH_FILE, - SERVICE_CMD_APP_FILE_READY, - SERVICE_CMD_APP_DONE, - SERVICE_CMD_START, - SERVICE_CMD_GET_EXT_FILE_NAME, - }; - - virtual ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) = 0; - virtual ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) = 0; - virtual ErrCode Start() = 0; - virtual UniqueFd GetLocalCapabilities() = 0; - virtual ErrCode PublishFile(const BFileInfo &fileInfo) = 0; - virtual ErrCode AppFileReady(const std::string &fileName, UniqueFd fd) = 0; - virtual ErrCode AppDone(ErrCode errCode) = 0; - virtual ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) = 0; - - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Backup.IService") -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_I_SERVICE_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h deleted file mode 100644 index 859773963..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_I_SERVICE_REVERSE_H -#define OHOS_FILEMGMT_BACKUP_I_SERVICE_REVERSE_H - -#include - -#include "iremote_broker.h" - -namespace OHOS::FileManagement::Backup { -class IServiceReverse : public IRemoteBroker { -public: - enum class Scenario { - UNDEFINED, - BACKUP, - RESTORE, - }; - - enum { - SERVICER_BACKUP_ON_FILE_READY, - SERVICER_BACKUP_ON_SUB_TASK_STARTED, - SERVICER_BACKUP_ON_SUB_TASK_FINISHED, - SERVICER_BACKUP_ON_TASK_FINISHED, - - SERVICER_RESTORE_ON_SUB_TASK_STARTED, - SERVICER_RESTORE_ON_SUB_TASK_FINISHED, - SERVICER_RESTORE_ON_TASK_FINISHED, - SERVICER_RESTORE_ON_FILE_READY, - }; - -public: - virtual void BackupOnFileReady(std::string bundleName, std::string fileName, int fd) = 0; - virtual void BackupOnBundleStarted(int32_t errCode, std::string bundleName) = 0; - virtual void BackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; - virtual void BackupOnAllBundlesFinished(int32_t errCode) = 0; - - virtual void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; - virtual void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) = 0; - virtual void RestoreOnAllBundlesFinished(int32_t errCode) = 0; - virtual void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) = 0; - - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileManagement.Backup.IServiceReverse") -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_I_SERVICE_REVERSE_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h deleted file mode 100644 index 9b3c8688c..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SERVICE_PROXY_H -#define OHOS_FILEMGMT_BACKUP_SERVICE_PROXY_H - -#include -#include -#include -#include - -#include "i_service.h" -#include "iremote_proxy.h" -#include "system_ability_load_callback_stub.h" - -namespace OHOS::FileManagement::Backup { -class ServiceProxy : public IRemoteProxy { -public: - ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) override; - ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) override; - ErrCode Start() override; - UniqueFd GetLocalCapabilities() override; - ErrCode PublishFile(const BFileInfo &fileInfo) override; - ErrCode AppFileReady(const std::string &fileName, UniqueFd fd) override; - ErrCode AppDone(ErrCode errCode) override; - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) override; - -public: - explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} - ~ServiceProxy() override {} - -public: - static sptr GetInstance(); - -public: - class ServiceProxyLoadCallback : public SystemAbilityLoadCallbackStub { - public: - void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr &remoteObject) override; - void OnLoadSystemAbilityFail(int32_t systemAbilityId) override; - - public: - std::condition_variable proxyConVar_; - std::atomic isLoadSuccess_ = {false}; - }; - -private: - static inline std::mutex proxyMutex_; - static inline sptr serviceProxy_ = nullptr; - static inline BrokerDelegator delegator_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SERVICE_PROXY_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/svc_death_recipient.h b/interfaces/inner_api/native/backup_kit_inner/impl/svc_death_recipient.h deleted file mode 100644 index d7d9d294d..000000000 --- a/interfaces/inner_api/native/backup_kit_inner/impl/svc_death_recipient.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SVC_DEATH_RECIPIENT_H -#define OHOS_FILEMGMT_BACKUP_SVC_DEATH_RECIPIENT_H - -#include - -#include "iremote_object.h" - -namespace OHOS::FileManagement::Backup { -class SvcDeathRecipient : public IRemoteObject::DeathRecipient { -public: - void OnRemoteDied(const wptr &object) override - { - object->RemoveDeathRecipient(this); - functor_(object); - }; - -public: - explicit SvcDeathRecipient(std::function &)> functor) : functor_(functor) {}; - -private: - std::function &)> functor_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SVC_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/5203.xml b/services/5203.xml deleted file mode 100644 index 9e204f7bb..000000000 --- a/services/5203.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - backup_sa - - libbackup_sa.z.so - - - 5203 - libbackup_sa.z.so - - - false - false - 1 - - diff --git a/services/BUILD.gn b/services/BUILD.gn deleted file mode 100644 index f1c6028b5..000000000 --- a/services/BUILD.gn +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//build/ohos/sa_profile/sa_profile.gni") - -group("backup_para_etc") { - deps = [ ":backup.para" ] -} - -ohos_sa_profile("backup_sa_profile") { - sources = [ "5203.xml" ] - part_name = "app_file_service" -} - -ohos_prebuilt_etc("backup_sa_etc") { - source = "backup.cfg" - relative_install_dir = "init" - part_name = "app_file_service" - subsystem_name = "filemanagement" -} - -ohos_prebuilt_etc("backup.para") { - source = "backup.para" - install_images = [ "system" ] - part_name = "app_file_service" - subsystem_name = "filemanagement" - relative_install_dir = "param" -} diff --git a/services/backup.cfg b/services/backup.cfg deleted file mode 100644 index 84d391ce6..000000000 --- a/services/backup.cfg +++ /dev/null @@ -1,11 +0,0 @@ -{ - "services" : [{ - "name" : "backup_sa", - "path" : ["/system/bin/sa_main", "/system/profile/backup_sa.xml"], - "ondemand" : true, - "uid" : "backup", - "gid" : ["backup"], - "secon" : "u:r:backup_sa:s0" - } - ] -} \ No newline at end of file diff --git a/services/backup.para b/services/backup.para deleted file mode 100644 index 73c5f0455..000000000 --- a/services/backup.para +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -backup.debug.overrideExtensionConfig=false \ No newline at end of file diff --git a/services/backup_sa/BUILD.gn b/services/backup_sa/BUILD.gn deleted file mode 100644 index d71e26ba0..000000000 --- a/services/backup_sa/BUILD.gn +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_shared_library("backup_sa") { - sources = [ - "src/module_ipc/service.cpp", - "src/module_ipc/service_reverse_proxy.cpp", - "src/module_ipc/service_stub.cpp", - "src/module_ipc/svc_backup_connection.cpp", - "src/module_ipc/svc_extension_proxy.cpp", - "src/module_ipc/svc_session_manager.cpp", - "src/module_sched/sched_scheduler.cpp", - ] - - defines = [ - "LOG_DOMAIN=0xD004303", - "LOG_TAG=\"BackupSA\"", - ] - - include_dirs = [ "include" ] - - deps = [ "${path_backup}/utils:backup_utils" ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "access_token:libaccesstoken_sdk", - "app_file_service:backup_kit_inner", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "init:libbegetutil", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - - use_exceptions = true - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h deleted file mode 100644 index 1a1ba2dec..000000000 --- a/services/backup_sa/include/module_ipc/service.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SERVICE_H -#define OHOS_FILEMGMT_BACKUP_SERVICE_H - -#include -#include - -#include "i_service_reverse.h" -#include "iremote_stub.h" -#include "module_sched/sched_scheduler.h" -#include "service_stub.h" -#include "svc_session_manager.h" -#include "system_ability.h" - -namespace OHOS::FileManagement::Backup { -class Service : public SystemAbility, public ServiceStub, protected NoCopyable { - DECLARE_SYSTEM_ABILITY(Service); - - // 以下都是IPC接口 -public: - ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) override; - ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) override; - ErrCode Start() override; - UniqueFd GetLocalCapabilities() override; - ErrCode PublishFile(const BFileInfo &fileInfo) override; - ErrCode AppFileReady(const std::string &fileName, UniqueFd fd) override; - ErrCode AppDone(ErrCode errCode) override; - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) override; - - // 以下都是非IPC接口 -public: - void OnStart() override; - void OnStop() override; - void StopAll(const wptr &obj, bool force = false); - int Dump(int fd, const std::vector &args) override; - - /** - * @brief 执行启动 backup extension - * - * @param bundleName - * @return ErrCode - */ - virtual ErrCode LaunchBackupExtension(const BundleName &bundleName); - - /** - * @brief backup extension died - * - * @param bundleName 应用名称 - */ - void OnBackupExtensionDied(const std::string &&bundleName, ErrCode ret); - - /** - * @brief extension启动连接成功 - * - * @param bundleName 应用名称 - */ - void ExtConnectDone(std::string bundleName); - - /** - * @brief extension启动连接失败 - * - * @param bundleName 应用名称 - */ - void ExtConnectFailed(const std::string &bundleName, ErrCode ret); - - /** - * @brief 执行backup extension 备份恢复流程 - * - * @param bundleName 应用名称 - */ - virtual void ExtStart(const std::string &bundleName); - -public: - explicit Service(int32_t saID, bool runOnCreate = false) : SystemAbility(saID, runOnCreate) - { - session_ = sptr(new SvcSessionManager(wptr(this))); - }; - ~Service() override = default; - -private: - /** - * @brief 验证调用者 - * - */ - void VerifyCaller(); - - /** - * @brief 验证调用者 - * - * @param scenario Scenario状态 - */ - void VerifyCaller(IServiceReverse::Scenario scenario); - - /** - * @brief 验证调用者并返回名称 - * - * @return std::string - */ - std::string VerifyCallerAndGetCallerName(); - - /** - * @brief 清除Session Sched相关资源 - * - * @param bundleName 应用名称 - */ - void ClearSessionAndSchedInfo(const std::string &bundleName); - -private: - static sptr instance_; - static std::mutex instanceLock_; - static inline std::atomic seed {1}; - - sptr session_; - sptr sched_; - - friend class ServiceTest; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SERVICE_H \ No newline at end of file diff --git a/services/backup_sa/include/module_ipc/service_reverse_proxy.h b/services/backup_sa/include/module_ipc/service_reverse_proxy.h deleted file mode 100644 index 5fd75cb57..000000000 --- a/services/backup_sa/include/module_ipc/service_reverse_proxy.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_PROXY_H -#define OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_PROXY_H - -#include "i_service_reverse.h" -#include "iremote_proxy.h" - -namespace OHOS::FileManagement::Backup { -class ServiceReverseProxy final : public IRemoteProxy, protected NoCopyable { -public: - void BackupOnFileReady(std::string bundleName, std::string fileName, int fd) override; - void BackupOnBundleStarted(int32_t errCode, std::string bundleName) override; - void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; - void BackupOnAllBundlesFinished(int32_t errCode) override; - - void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; - void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; - void RestoreOnAllBundlesFinished(int32_t errCode) override; - void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) override; - -public: - explicit ServiceReverseProxy(const sptr &impl) : IRemoteProxy(impl) {} - ~ServiceReverseProxy() override = default; - -private: - static inline BrokerDelegator delegator_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SERVICE_REVERSE_PROXY_H \ No newline at end of file diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h deleted file mode 100644 index fb2e0782b..000000000 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SERVICE_STUB_H -#define OHOS_FILEMGMT_BACKUP_SERVICE_STUB_H - -#include - -#include "i_service.h" -#include "iremote_stub.h" - -namespace OHOS::FileManagement::Backup { -class ServiceStub : public IRemoteStub { -public: - int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - -public: - ServiceStub(); - ~ServiceStub() override = default; - -private: - using ServiceInterface = int32_t (ServiceStub::*)(MessageParcel &data, MessageParcel &reply); - std::map opToInterfaceMap_; - - int32_t CmdInitRestoreSession(MessageParcel &data, MessageParcel &reply); - int32_t CmdInitBackupSession(MessageParcel &data, MessageParcel &reply); - int32_t CmdStart(MessageParcel &data, MessageParcel &reply); - int32_t CmdGetLocalCapabilities(MessageParcel &data, MessageParcel &reply); - int32_t CmdPublishFile(MessageParcel &data, MessageParcel &reply); - int32_t CmdAppFileReady(MessageParcel &data, MessageParcel &reply); - int32_t CmdAppDone(MessageParcel &data, MessageParcel &reply); - int32_t CmdGetExtFileName(MessageParcel &data, MessageParcel &reply); -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SERVICE_STUB_H \ No newline at end of file diff --git a/services/backup_sa/include/module_ipc/svc_backup_connection.h b/services/backup_sa/include/module_ipc/svc_backup_connection.h deleted file mode 100644 index 91d46b562..000000000 --- a/services/backup_sa/include/module_ipc/svc_backup_connection.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SVC_BACKUP_CONNECTION_H -#define OHOS_FILEMGMT_BACKUP_SVC_BACKUP_CONNECTION_H - -#include "ability_connect_callback_stub.h" -#include "i_extension.h" - -namespace OHOS::FileManagement::Backup { -class SvcBackupConnection : public AAFwk::AbilityConnectionStub { -public: - /** - * @brief This method is called back to receive the connection result after an ability calls the - * ConnectAbility method to connect it to an extension ability. - * - * @param element: Indicates information about the connected extension ability. - * @param remote: Indicates the remote proxy object of the extension ability. - * @param resultCode: Indicates the connection result code. The value 0 indicates a successful connection, and any - * other value indicates a connection failure. - */ - void OnAbilityConnectDone(const AppExecFwk::ElementName &element, - const sptr &remoteObject, - int resultCode) override; - - /** - * @brief This method is called back to receive the disconnection result after the connected extension ability - * crashes or is killed. If the extension ability exits unexpectedly, all its connections are disconnected, and - * each ability previously connected to it will call onAbilityDisconnectDone. - * - * @param element: Indicates information about the disconnected extension ability. - * @param resultCode: Indicates the disconnection result code. The value 0 indicates a successful disconnection, - * and any other value indicates a disconnection failure. - */ - void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - - /** - * @brief connect remote ability of ExtBackup. - */ - ErrCode ConnectBackupExtAbility(AAFwk::Want &want); - - /** - * @brief disconnect remote ability of ExtBackup. - */ - ErrCode DisconnectBackupExtAbility(); - - /** - * @brief check whether connected to remote extension ability. - * - * @return bool true if connected, otherwise false. - */ - bool IsExtAbilityConnected(); - - /** - * @brief get the proxy of backup extension ability. - * - * @return the proxy of backup extension ability. - */ - sptr GetBackupExtProxy(); - -public: - SvcBackupConnection(std::function callDied, - std::function callConnDone) - : callDied_(callDied), callConnDone_(callConnDone) - { - } - ~SvcBackupConnection() override {}; - -private: - std::mutex mutex_; - std::condition_variable condition_; - std::atomic isConnected_ = {false}; - std::atomic isConnectedDone_ = {false}; - sptr backupProxy_; - - std::function callDied_; - std::function callConnDone_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SVC_BACKUP_CONNECTION_H \ No newline at end of file diff --git a/services/backup_sa/include/module_ipc/svc_extension_proxy.h b/services/backup_sa/include/module_ipc/svc_extension_proxy.h deleted file mode 100644 index 7711ed896..000000000 --- a/services/backup_sa/include/module_ipc/svc_extension_proxy.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SVC_EXTENSION_PROXY_H -#define OHOS_FILEMGMT_BACKUP_SVC_EXTENSION_PROXY_H - -#include "i_extension.h" -#include "iremote_proxy.h" - -namespace OHOS::FileManagement::Backup { -class SvcExtensionProxy : public IRemoteProxy { -public: - UniqueFd GetFileHandle(const std::string &fileName) override; - ErrCode HandleClear() override; - ErrCode HandleBackup() override; - ErrCode PublishFile(const std::string &fileName) override; - -public: - explicit SvcExtensionProxy(const sptr &remote) : IRemoteProxy(remote) {} - -private: - static inline BrokerDelegator delegator_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SVC_EXTENSION_PROXY_H \ No newline at end of file diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h deleted file mode 100644 index 48c2b3fba..000000000 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 说明: - * 备份服务同一时间只接受一个唯一的会话。在会话期间,服务只与一个备份应用通信 - * 且只响应备份或恢复接口中的一种。 - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SVC_SESSION_MANAGER_H -#define OHOS_FILEMGMT_BACKUP_SVC_SESSION_MANAGER_H - -#include -#include -#include -#include -#include - -#include "b_file_info.h" -#include "b_resources/b_constants.h" -#include "bundlemgr/bundle_mgr_interface.h" -#include "i_service_reverse.h" -#include "module_ipc/svc_backup_connection.h" -#include "svc_death_recipient.h" - -namespace OHOS::FileManagement::Backup { -struct BackupExtInfo { - bool receExtManageJson {false}; - bool receExtAppDone {false}; - std::string backupExtName; - sptr backUpConnection; - std::set fileNameInfo; - BConstants::ServiceSchedAction schedAction {BConstants::ServiceSchedAction::WAIT}; -}; - -class Service; -class SvcSessionManager : public virtual RefBase { -public: - struct Impl { - uint32_t clientToken {0}; - IServiceReverse::Scenario scenario {IServiceReverse::Scenario::UNDEFINED}; - std::map backupExtNameMap; - sptr clientProxy; - }; - -public: - /** - * @brief 检验调用者是否是会话所有者,且当前命令是否与当前场景相匹配 - * - * @param clientToken 调用者TOKEN - * @param scenario 给定场景 - * @throw BError::Codes::SA_REFUSED_ACT 调用者不是会话所有者 - * @throw BError::Codes::SDK_MIXED_SCENARIO 调用者在备份/恢复场景使用了不匹配的函数 - */ - void VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const; - - /** - * @brief 激活会话 - * - * @param impl 客户端信息 - */ - void Active(Impl newImpl); - - /** - * @brief 关闭会话 - * - * @param remoteInAction 尝试关闭会话的客户端代理。只有激活会话的客户端代理有权关闭会话 - * @param force 强制关闭 - */ - void Deactive(const wptr &remoteInAction, bool force = false); - - /** - * @brief 检验调用者给定的bundleName是否是有效的 - * - * @param bundleName 调用者名称 - * @throw BError::Codes::SA_REFUSED_ACT 调用者不是会话所有者 - */ - void VerifyBundleName(std::string &bundleName); - - /** - * @brief 获取IServiceReverse - * - * @return sptr 返回clientProxy - * @throw BError::Codes::SA_REFUSED_ACT 调用者不是会话所有者 - */ - sptr GetServiceReverseProxy(); - - /** - * @brief 获取Scenario - * - * @return IServiceReverse::Scenario 返回scenario - * @throw BError::Codes::SA_INVAL_ARG 获取异常 - */ - IServiceReverse::Scenario GetScenario(); - - /** - * @brief 更新backupExtNameMap并判断是否完成分发 - * - * @param bundleName 客户端信息 - * @param fileName 文件名称 - * @throw BError::Codes::SA_INVAL_ARG 获取异常 - * @return true 分发已完成 - * @return false 分发未完成 - */ - bool OnBunleFileReady(const std::string &bundleName, const std::string &fileName = ""); - - /** - * @brief 设置backup manage.json 信息 - * - * @param bundleName 客户端信息 - * @param fd manage.json 文件描述符 - * @return UniqueFd 返回manage.json 文件描述符 - * @throw BError::Codes::SA_INVAL_ARG 获取异常 - */ - UniqueFd OnBunleExtManageInfo(const std::string &bundleName, UniqueFd fd); - - /** - * @brief Remove backup extension info - * - * @param bundleName 应用名称 - */ - void RemoveExtInfo(const std::string &bundleName); - - /** - * @brief get extension connection info - * - * @param bundleName - * @return wptr - */ - wptr GetExtConnection(const BundleName &bundleName); - - /** - * @brief HiDumper dump info - * - * @param fd 对端dump句柄 - * @param args 服务参数 - */ - void DumpInfo(const int fd, const std::vector &args); - - /** - * @brief 暂存restore流程真实文件请求 - * - * @param bundleName 应用名称 - * @param fileName 文件名称 - */ - void SetExtFileNameRequest(const std::string &bundleName, const std::string &fileName); - - /** - * @brief 获取restore流程真实文件请求 - * - * @param bundleName 应用名称 - * @return std::set 返回真实文件vec - */ - std::set GetExtFileNameRequest(const std::string &bundleName); - - /** - * @brief 获取ServiceSchedAction状态 - * - * @param bundleName 应用名称 - * @return BConstants::ServiceSchedAction - */ - BConstants::ServiceSchedAction GetServiceSchedAction(const std::string &bundleName); - - /** - * @brief 设置ServiceSchedAction状态 - * - * @param bundleName 应用名称 - * @param action 状态 - */ - void SetServiceSchedAction(const std::string &bundleName, BConstants::ServiceSchedAction action); - - /** - * @brief 获取所需要的调度信息 - * - * @return std::string 返回bundleName - */ - bool GetSchedBundleName(std::string &bundleName); - - /** - * @brief 获取backup extension name - * - * @param bundleName 应用名称 - * @return std::string - * @return std::string extension name - */ - std::string GetBackupExtName(const std::string &bundleName); - -private: - /** - * @brief 校验BundleName和ability type 并补全Impl.backupExtNameMap信息 - * - * @param backupExtNameMap 客户端信息 - * @throw BError::Codes::SA_INVAL_ARG 客户端信息异常 - * @throw BError::Codes::SA_BROKEN_IPC - */ - virtual void GetBundleExtNames(std::map &backupExtNameMap); - - /** - * @brief 初始化 extension backUpConnection - * - * @param backupExtNameMap - */ - virtual void InitExtConn(std::map &backupExtNameMap); - - /** - * @brief 初始化 clientProxy - * - * @param newImpl - */ - virtual void InitClient(Impl &newImpl); - - /** - * @brief 获取BackupExtNameMap iterator - * - * @param bundleName 应用名称 - * @return std::map::iterator - */ - std::map::iterator GetBackupExtNameMap(const std::string &bundleName); - -public: - /** - * @brief Construct a new Svc Session object - * - * @param reversePtr 指向Service的反向指针,使用wptr避免循环引用 - */ - explicit SvcSessionManager(wptr reversePtr) : reversePtr_(reversePtr) {} - ~SvcSessionManager() override = default; - -private: - sptr GetBundleManager(); - - mutable std::shared_mutex lock_; - wptr reversePtr_; - sptr deathRecipient_; - Impl impl_; - uint32_t extConnectNum_ {0}; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SVC_SESSION_MANAGER_H diff --git a/services/backup_sa/include/module_sched/sched_scheduler.h b/services/backup_sa/include/module_sched/sched_scheduler.h deleted file mode 100644 index b84f4c134..000000000 --- a/services/backup_sa/include/module_sched/sched_scheduler.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_SCHED_SCHEDULER_H -#define OHOS_FILEMGMT_BACKUP_SCHED_SCHEDULER_H - -#include -#include -#include -#include -#include - -#include "b_resources/b_constants.h" -#include "iremote_broker.h" -#include "thread_pool.h" -#include "timer.h" - -namespace OHOS::FileManagement::Backup { -class Service; -class SvcSessionManager; - -class SchedScheduler final : public virtual RefBase { -public: - /** - * @brief 给threadPool下发任务 - * - */ - void Sched(std::string bundleName = ""); - - /** - * @brief 执行队列任务 - * - * @param bundleName - */ - void ExecutingQueueTasks(const std::string &bundleName); - - /** - * @brief 移除定时器信息 - * - * @param bundleName 应用名称 - */ - void RemoveExtConn(const std::string &bundleName); - - void StartTimer() - { - extTime_.Setup(); - } - -public: - explicit SchedScheduler(wptr reversePtr, wptr sessionPtr) - : reversePtr_(reversePtr), sessionPtr_(sessionPtr) - { - threadPool_.Start(BConstants::SA_THREAD_POOL_COUNT); - } - - ~SchedScheduler() override - { - extTime_.Shutdown(); - reversePtr_ = nullptr; - sessionPtr_ = nullptr; - bundleTimeVec_.clear(); - } - -private: - mutable std::shared_mutex lock_; - OHOS::ThreadPool threadPool_; - - // 注册心跳信息 - std::vector> bundleTimeVec_; - - wptr reversePtr_; - wptr sessionPtr_; - Utils::Timer extTime_ {"backupSchedTimer"}; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_SCHED_SCHEDULER_H diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp deleted file mode 100644 index b6debaa69..000000000 --- a/services/backup_sa/src/module_ipc/service.cpp +++ /dev/null @@ -1,544 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 注意: - * - 注意点1:本文件原则上只处理与IPC无关的业务逻辑 - * - 注意点2:This document, in principle, captures all exceptions. - * Prevent exceptions from spreading to insecure modules. - */ -#include "module_ipc/service.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include "ability_manager_client.h" -#include "accesstoken_kit.h" -#include "b_error/b_error.h" -#include "b_file_info.h" -#include "b_json/b_json_cached_entity.h" -#include "b_json/b_json_entity_caps.h" -#include "b_process/b_multiuser.h" -#include "b_process/b_process.h" -#include "b_resources/b_constants.h" -#include "bundle_mgr_client.h" -#include "filemgmt_libhilog.h" -#include "ipc_skeleton.h" -#include "module_ipc/svc_backup_connection.h" -#include "parameter.h" -#include "system_ability_definition.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -REGISTER_SYSTEM_ABILITY_BY_ID(Service, FILEMANAGEMENT_BACKUP_SERVICE_SA_ID, false); - -void Service::OnStart() -{ - bool res = SystemAbility::Publish(sptr(this)); - sched_ = sptr(new SchedScheduler(wptr(this), wptr(session_))); - sched_->StartTimer(); - HILOGI("End, res = %{public}d", res); -} - -void Service::OnStop() -{ - HILOGI("Called"); - sched_ = nullptr; - session_ = nullptr; -} - -UniqueFd Service::GetLocalCapabilities() -{ - try { - VerifyCaller(); - struct statfs fsInfo = {}; - if (statfs(BConstants::SA_BUNDLE_BACKUP_ROOT_DIR.data(), &fsInfo) == -1) { - throw BError(errno); - } - - BJsonCachedEntity cachedEntity( - UniqueFd(open(BConstants::SA_BUNDLE_BACKUP_ROOT_DIR.data(), O_TMPFILE | O_RDWR, 0600))); - auto cache = cachedEntity.Structuralize(); - cache.SetFreeDiskSpace(fsInfo.f_bfree); - cache.SetOSFullName(GetOSFullName()); - cache.SetDeviceType(GetDeviceType()); - cachedEntity.Persist(); - - return move(cachedEntity.GetFd()); - } catch (const BError &e) { - return UniqueFd(-e.GetCode()); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return UniqueFd(-EPERM); - } catch (...) { - HILOGI("Unexpected exception"); - return UniqueFd(-EPERM); - } -} - -void Service::StopAll(const wptr &obj, bool force) -{ - session_->Deactive(obj, force); -} - -string Service::VerifyCallerAndGetCallerName() -{ - uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); - int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); - if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { - const string permission = "ohos.permission.BACKUP"; - int ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission); - if (ret == Security::AccessToken::TypePermissionState::PERMISSION_DENIED) { - throw BError(BError::Codes::SA_INVAL_ARG, - string("Permission denied, token type is ").append(to_string(tokenType))); - } - Security::AccessToken::HapTokenInfo hapTokenInfo; - if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) { - throw BError(BError::Codes::SA_INVAL_ARG, "Get hap token info failed"); - } - session_->VerifyBundleName(hapTokenInfo.bundleName); - return hapTokenInfo.bundleName; - } else { - throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType))); - } -} - -void Service::VerifyCaller() -{ - uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); - int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); - switch (tokenType) { - case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: { - auto multiuser = BMultiuser::ParseUid(IPCSkeleton::GetCallingUid()); - if (multiuser.userId != BConstants::DEFAULT_USER_ID) { - throw BError(BError::Codes::SA_INVAL_ARG, string("Calling user is ") - .append(to_string(multiuser.userId)) - .append(", which is currently not supported")); - } - const string permission = "ohos.permission.BACKUP"; - if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - Security::AccessToken::TypePermissionState::PERMISSION_DENIED) { - throw BError(BError::Codes::SA_INVAL_ARG, - string("Permission denied, token type is ").append(to_string(tokenType))); - } - break; - } - case Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL: - if (IPCSkeleton::GetCallingUid() != BConstants::SYSTEM_UID) { - throw BError(BError::Codes::SA_INVAL_ARG, "Calling uid is invalid"); - } - break; - default: - throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType))); - break; - } -} - -void Service::VerifyCaller(IServiceReverse::Scenario scenario) -{ - session_->VerifyCallerAndScenario(IPCSkeleton::GetCallingTokenID(), scenario); - VerifyCaller(); -} - -ErrCode Service::InitRestoreSession(sptr remote, const vector &bundleNames) -{ - try { - VerifyCaller(); - map backupExtNameMap; - auto setBackupExtNameMap = [](const BundleName &bundleName) { - BackupExtInfo info {}; - return make_pair(bundleName, info); - }; - transform(bundleNames.begin(), bundleNames.end(), inserter(backupExtNameMap, backupExtNameMap.end()), - setBackupExtNameMap); - session_->Active({ - .clientToken = IPCSkeleton::GetCallingTokenID(), - .scenario = IServiceReverse::Scenario::RESTORE, - .backupExtNameMap = move(backupExtNameMap), - .clientProxy = remote, - }); - return BError(BError::Codes::OK); - } catch (const BError &e) { - StopAll(nullptr, true); - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -ErrCode Service::InitBackupSession(sptr remote, UniqueFd fd, const vector &bundleNames) -{ - try { - VerifyCaller(); - map backupExtNameMap; - auto setBackupExtNameMap = [](const BundleName &bundleName) { - BackupExtInfo info {}; - return make_pair(bundleName, info); - }; - transform(bundleNames.begin(), bundleNames.end(), inserter(backupExtNameMap, backupExtNameMap.end()), - setBackupExtNameMap); - session_->Active({ - .clientToken = IPCSkeleton::GetCallingTokenID(), - .scenario = IServiceReverse::Scenario::BACKUP, - .backupExtNameMap = move(backupExtNameMap), - .clientProxy = remote, - }); - - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - uint64_t size = cache.GetFreeDiskSpace(); - if (size == 0) { - throw BError(BError::Codes::SA_INVAL_ARG, "Invalid field FreeDiskSpace or unsufficient space"); - } - return BError(BError::Codes::OK); - } catch (const BError &e) { - StopAll(nullptr, true); - return e.GetCode(); - } -} - -ErrCode Service::Start() -{ - try { - HILOGI("Begin"); - VerifyCaller(session_->GetScenario()); - for (int num = 0; num < BConstants::EXT_CONNECT_MAX_COUNT; num++) { - sched_->Sched(); - } - return BError(BError::Codes::OK); - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -ErrCode Service::PublishFile(const BFileInfo &fileInfo) -{ - try { - HILOGI("Begin"); - VerifyCaller(IServiceReverse::Scenario::RESTORE); - - if (!regex_match(fileInfo.fileName, regex("^[0-9a-zA-Z_.]+$"))) { - throw BError(BError::Codes::SA_INVAL_ARG, "Filename is not alphanumeric"); - } - - auto backUpConnection = session_->GetExtConnection(fileInfo.owner); - - auto proxy = backUpConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - ErrCode res = proxy->PublishFile(fileInfo.fileName); - if (res) { - HILOGE("Failed to publish file for backup extension"); - } - - return BError(BError::Codes::OK); - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd) -{ - try { - HILOGE("begin %{public}s", fileName.data()); - string callerName = VerifyCallerAndGetCallerName(); - if (!regex_match(fileName, regex("^[0-9a-zA-Z_.]+$"))) { - throw BError(BError::Codes::SA_INVAL_ARG, "Filename is not alphanumeric"); - } - if (fileName == BConstants::EXT_BACKUP_MANAGE) { - fd = session_->OnBunleExtManageInfo(callerName, move(fd)); - } - - session_->GetServiceReverseProxy()->BackupOnFileReady(callerName, fileName, move(fd)); - - if (session_->OnBunleFileReady(callerName, fileName)) { - auto backUpConnection = session_->GetExtConnection(callerName); - auto proxy = backUpConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - // 通知extension清空缓存 - proxy->HandleClear(); - // 通知TOOL 备份完成 - session_->GetServiceReverseProxy()->BackupOnBundleFinished(BError(BError::Codes::OK), callerName); - // 断开extension - backUpConnection->DisconnectBackupExtAbility(); - ClearSessionAndSchedInfo(callerName); - } - return BError(BError::Codes::OK); - } catch (const BError &e) { - return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -ErrCode Service::AppDone(ErrCode errCode) -{ - try { - HILOGI("Begin"); - string callerName = VerifyCallerAndGetCallerName(); - if (session_->OnBunleFileReady(callerName)) { - auto backUpConnection = session_->GetExtConnection(callerName); - auto proxy = backUpConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - proxy->HandleClear(); - IServiceReverse::Scenario scenario = session_->GetScenario(); - if (scenario == IServiceReverse::Scenario::BACKUP) { - session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, callerName); - } else if (scenario == IServiceReverse::Scenario::RESTORE) { - session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, callerName); - } - backUpConnection->DisconnectBackupExtAbility(); - ClearSessionAndSchedInfo(callerName); - } - return BError(BError::Codes::OK); - } catch (const BError &e) { - return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) -{ - try { - HILOGE("begin %{public}s", bundleName.data()); - IServiceReverse::Scenario scenario = session_->GetScenario(); - BConstants::ExtensionAction action; - if (scenario == IServiceReverse::Scenario::BACKUP) { - action = BConstants::ExtensionAction::BACKUP; - } else if (scenario == IServiceReverse::Scenario::RESTORE) { - action = BConstants::ExtensionAction::RESTORE; - } else { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to scenario"); - } - - AAFwk::Want want; - string backupExtName = session_->GetBackupExtName(bundleName); - want.SetElementName(bundleName, backupExtName); - want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); - - auto backUpConnection = session_->GetExtConnection(bundleName); - ErrCode ret = backUpConnection->ConnectBackupExtAbility(want); - return ret; - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -ErrCode Service::GetExtFileName(string &bundleName, string &fileName) -{ - try { - HILOGE("begin"); - VerifyCaller(IServiceReverse::Scenario::RESTORE); - session_->SetExtFileNameRequest(bundleName, fileName); - return BError(BError::Codes::OK); - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -void Service::OnBackupExtensionDied(const string &&bundleName, ErrCode ret) -{ - try { - HILOGI("extension died. Died bundleName = %{public}s", bundleName.data()); - string callName = move(bundleName); - session_->VerifyBundleName(callName); - auto scenario = session_->GetScenario(); - if (scenario == IServiceReverse::Scenario::BACKUP) { - session_->GetServiceReverseProxy()->BackupOnBundleFinished(ret, callName); - } else if (scenario == IServiceReverse::Scenario::RESTORE) { - session_->GetServiceReverseProxy()->RestoreOnBundleFinished(ret, callName); - } - auto backUpConnection = session_->GetExtConnection(callName); - if (backUpConnection->IsExtAbilityConnected()) { - backUpConnection->DisconnectBackupExtAbility(); - } - ClearSessionAndSchedInfo(bundleName); - } catch (const BError &e) { - return; - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return; - } catch (...) { - HILOGI("Unexpected exception"); - return; - } -} - -void Service::ExtStart(const string &bundleName) -{ - try { - HILOGE("begin %{public}s", bundleName.data()); - IServiceReverse::Scenario scenario = session_->GetScenario(); - auto backUpConnection = session_->GetExtConnection(bundleName); - auto proxy = backUpConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - if (scenario == IServiceReverse::Scenario::BACKUP) { - auto ret = proxy->HandleBackup(); - session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); - if (ret) { - ClearSessionAndSchedInfo(bundleName); - } - return; - } - if (scenario != IServiceReverse::Scenario::RESTORE) { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to scenario"); - } - session_->GetServiceReverseProxy()->RestoreOnBundleStarted(BError(BError::Codes::OK), bundleName); - auto fileNameVec = session_->GetExtFileNameRequest(bundleName); - for (auto &fileName : fileNameVec) { - UniqueFd fd = proxy->GetFileHandle(fileName); - if (fd < 0) { - HILOGE("Failed to extension file handle"); - OnBackupExtensionDied(move(bundleName), fd); - return; - } - session_->GetServiceReverseProxy()->RestoreOnFileReady(bundleName, fileName, move(fd)); - } - return; - } catch (const BError &e) { - return; - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return; - } catch (...) { - HILOGI("Unexpected exception"); - return; - } -} - -int Service::Dump(int fd, const vector &args) -{ - if (fd < 0) { - HILOGI("HiDumper handle invalid"); - return -1; - } - - session_->DumpInfo(fd, args); - return 0; -} - -void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) -{ - try { - HILOGE("begin %{public}s", bundleName.data()); - IServiceReverse::Scenario scenario = session_->GetScenario(); - if (scenario == IServiceReverse::Scenario::BACKUP) { - session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); - } else if (scenario == IServiceReverse::Scenario::RESTORE) { - session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); - } - ClearSessionAndSchedInfo(bundleName); - return; - } catch (const BError &e) { - return; - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return; - } catch (...) { - HILOGI("Unexpected exception"); - return; - } -} - -void Service::ExtConnectDone(string bundleName) -{ - try { - HILOGE("begin %{public}s", bundleName.data()); - session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::RUNNING); - sched_->Sched(bundleName); - } catch (const BError &e) { - return; - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return; - } catch (...) { - HILOGI("Unexpected exception"); - return; - } -} - -void Service::ClearSessionAndSchedInfo(const string &bundleName) -{ - try { - session_->RemoveExtInfo(bundleName); - sched_->RemoveExtConn(bundleName); - sched_->Sched(); - } catch (const BError &e) { - return; - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return; - } catch (...) { - HILOGI("Unexpected exception"); - return; - } -} -} // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp b/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp deleted file mode 100644 index 26cfa7748..000000000 --- a/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/service_reverse_proxy.h" - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void ServiceReverseProxy::BackupOnFileReady(string bundleName, string fileName, int fd) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(fileName) || - !data.WriteFileDescriptor(fd)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - } - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_BACKUP_ON_FILE_READY, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} - -void ServiceReverseProxy::BackupOnBundleStarted(int32_t errCode, string bundleName) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - }; - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_BACKUP_ON_SUB_TASK_STARTED, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} - -void ServiceReverseProxy::BackupOnBundleFinished(int32_t errCode, string bundleName) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - } - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_BACKUP_ON_SUB_TASK_FINISHED, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} - -void ServiceReverseProxy::BackupOnAllBundlesFinished(int32_t errCode) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - } - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_BACKUP_ON_TASK_FINISHED, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} - -void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - } - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_RESTORE_ON_SUB_TASK_STARTED, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} - -void ServiceReverseProxy::RestoreOnBundleFinished(int32_t errCode, string bundleName) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - } - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_RESTORE_ON_SUB_TASK_FINISHED, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} - -void ServiceReverseProxy::RestoreOnAllBundlesFinished(int32_t errCode) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - } - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_RESTORE_ON_TASK_FINISHED, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} - -void ServiceReverseProxy::RestoreOnFileReady(string bundleName, string fileName, int fd) -{ - HILOGI("Begin"); - MessageParcel data; - if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(fileName) || - !data.WriteFileDescriptor(fd)) { - throw BError(BError::Codes::SA_BROKEN_IPC); - } - - MessageParcel reply; - MessageOption option; - if (int err = Remote()->SendRequest(IServiceReverse::SERVICER_RESTORE_ON_FILE_READY, data, reply, option); - err != ERR_OK) { - throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); - } -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp deleted file mode 100644 index 8134ca92a..000000000 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 注意: - * - 注意点1:本文件原则上只处理与IPC模块的IO,具体业务逻辑实现在service.cpp中 - * - 注意点2:所有调用开头处打印 Begin 字样,通过BError返回正常结果/错误码,这是出于防抵赖的目的 - */ - -#include "module_ipc/service_stub.h" - -#include - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" -#include "module_ipc/service_reverse_proxy.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -ServiceStub::ServiceStub() -{ - opToInterfaceMap_[SERVICE_CMD_INIT_RESTORE_SESSION] = &ServiceStub::CmdInitRestoreSession; - opToInterfaceMap_[SERVICE_CMD_INIT_BACKUP_SESSION] = &ServiceStub::CmdInitBackupSession; - opToInterfaceMap_[SERVICE_CMD_GET_LOCAL_CAPABILITIES] = &ServiceStub::CmdGetLocalCapabilities; - opToInterfaceMap_[SERVICE_CMD_PUBLISH_FILE] = &ServiceStub::CmdPublishFile; - opToInterfaceMap_[SERVICE_CMD_APP_FILE_READY] = &ServiceStub::CmdAppFileReady; - opToInterfaceMap_[SERVICE_CMD_APP_DONE] = &ServiceStub::CmdAppDone; - opToInterfaceMap_[SERVICE_CMD_START] = &ServiceStub::CmdStart; - opToInterfaceMap_[SERVICE_CMD_GET_EXT_FILE_NAME] = &ServiceStub::CmdGetExtFileName; -} - -int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - HILOGI("Begin to call procedure indexed %{public}u", code); - auto interfaceIndex = opToInterfaceMap_.find(code); - if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { - stringstream ss; - ss << "Cannot response request " << code << ": unknown procedure"; - return BError(BError::Codes::SA_INVAL_ARG, ss.str()); - } - - const std::u16string descriptor = ServiceStub::GetDescriptor(); - const std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - return BError(BError::Codes::SA_INVAL_ARG, "Invalid remote descriptor"); - } - - return (this->*(interfaceIndex->second))(data, reply); -} - -int32_t ServiceStub::CmdInitRestoreSession(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - auto remote = data.ReadRemoteObject(); - if (!remote) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); - } - auto iremote = iface_cast(remote); - if (!iremote) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); - } - - std::vector bundleNames; - if (!data.ReadStringVector(&bundleNames)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); - } - - int32_t res = InitRestoreSession(iremote, bundleNames); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::SA_BROKEN_IPC, ss.str()); - } - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - auto remote = data.ReadRemoteObject(); - if (!remote) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); - } - auto iremote = iface_cast(remote); - if (!remote) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); - } - - UniqueFd fd(data.ReadFileDescriptor()); - if (fd < 0) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fd"); - } - - std::vector bundleNames; - if (!data.ReadStringVector(&bundleNames)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); - } - - int res = InitBackupSession(iremote, move(fd), bundleNames); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::SA_BROKEN_IPC, ss.str()); - } - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdStart(MessageParcel &data, MessageParcel &reply) -{ - int res = Start(); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::SA_BROKEN_IPC, ss.str()); - } - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdGetLocalCapabilities(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - UniqueFd fd(GetLocalCapabilities()); - if (!reply.WriteFileDescriptor(fd)) { - return BError(BError::Codes::SA_BROKEN_IPC, "Failed to send out the file"); - } - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdPublishFile(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - unique_ptr fileInfo(data.ReadParcelable()); - if (!fileInfo) { - return BError(BError::Codes::SA_BROKEN_IPC, "Failed to receive fileInfo"); - } - int res = PublishFile(*fileInfo); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::SA_BROKEN_IPC, ss.str()); - } - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdAppFileReady(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - string fileName; - if (!data.ReadString(fileName)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fileName"); - } - UniqueFd fd(data.ReadFileDescriptor()); - if (fd < 0) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fd"); - } - - int res = AppFileReady(fileName, move(fd)); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::SA_BROKEN_IPC, ss.str()); - } - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdAppDone(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - bool success; - if (!data.ReadBool(success)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bool flag"); - } - int res = AppDone(success); - if (!reply.WriteInt32(res)) { - stringstream ss; - ss << "Failed to send the result " << res; - return BError(BError::Codes::SA_BROKEN_IPC, ss.str()); - } - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdGetExtFileName(MessageParcel &data, MessageParcel &reply) -{ - HILOGI("Begin"); - string bundleName; - if (!data.ReadString(bundleName)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleName").GetCode(); - } - string fileName; - if (!data.ReadString(fileName)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fileName").GetCode(); - } - - return GetExtFileName(bundleName, fileName); -} -} // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp deleted file mode 100644 index 18265e6ac..000000000 --- a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/svc_backup_connection.h" - -#include "ability_manager_client.h" -#include "filemgmt_libhilog.h" -#include "module_ipc/svc_extension_proxy.h" -#include "module_ipc/svc_session_manager.h" - -namespace OHOS::FileManagement::Backup { -constexpr int WAIT_TIME = 3; -using namespace std; - -void SvcBackupConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &element, - const sptr &remoteObject, - int resultCode) -{ - HILOGI("called begin"); - if (remoteObject == nullptr) { - HILOGE("Failed to ability connect done, remote is nullptr"); - return; - } - backupProxy_ = iface_cast(remoteObject); - if (backupProxy_ == nullptr) { - HILOGE("Failed to ability connect done, backupProxy_ is nullptr"); - return; - } - isConnected_.store(true); - string bundleName = element.GetBundleName(); - callConnDone_(move(bundleName)); - HILOGI("called end"); -} - -void SvcBackupConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) -{ - HILOGI("called begin"); - if (isConnectedDone_ == false) { - string bundleName = element.GetBundleName(); - HILOGE("It's error that the backup extension dies before the backup sa. name : %{public}s", bundleName.data()); - callDied_(move(bundleName)); - } - backupProxy_ = nullptr; - isConnected_.store(false); - condition_.notify_all(); - HILOGI("called end"); -} - -ErrCode SvcBackupConnection::ConnectBackupExtAbility(AAFwk::Want &want) -{ - HILOGI("called begin"); - std::unique_lock lock(mutex_); - ErrCode ret = - AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, this, AppExecFwk::Constants::START_USERID); - HILOGI("called end, ret=%{public}d", ret); - return ret; -} - -ErrCode SvcBackupConnection::DisconnectBackupExtAbility() -{ - HILOGI("called begin"); - isConnectedDone_.store(true); - std::unique_lock lock(mutex_); - ErrCode ret = AppExecFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(this); - auto callback = [extConn {wptr(this)}] { - auto extPtr = extConn.promote(); - if (!extPtr) { - HILOGE("Dis connect failed"); - return false; - } - return extPtr->GetBackupExtProxy() == nullptr; - }; - if (condition_.wait_for(lock, std::chrono::seconds(WAIT_TIME), callback)) { - HILOGI("Wait until the connection ends"); - } - HILOGI("called end, ret=%{public}d", ret); - return ret; -} - -bool SvcBackupConnection::IsExtAbilityConnected() -{ - return isConnected_.load(); -} - -sptr SvcBackupConnection::GetBackupExtProxy() -{ - return backupProxy_; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp deleted file mode 100644 index 24f535fd3..000000000 --- a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/svc_extension_proxy.h" - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -UniqueFd SvcExtensionProxy::GetFileHandle(const string &fileName) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - if (!data.WriteString(fileName)) { - BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fileName"); - return UniqueFd(-1); - } - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IExtension::CMD_GET_FILE_HANDLE, data, reply, option); - if (ret != NO_ERROR) { - HILOGE("Received error %{public}d when doing IPC", ret); - return UniqueFd(-ret); - } - - HILOGI("Successful"); - UniqueFd fd(reply.ReadFileDescriptor()); - return UniqueFd(fd.Release()); -} - -ErrCode SvcExtensionProxy::HandleClear() -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IExtension::CMD_HANDLE_CLAER, data, reply, option); - if (ret != NO_ERROR) { - HILOGE("Received error %{public}d when doing IPC", ret); - return ErrCode(ret); - } - - HILOGI("Successful"); - return reply.ReadInt32(); -} - -ErrCode SvcExtensionProxy::HandleBackup() -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IExtension::CMD_HANDLE_BACKUP, data, reply, option); - if (ret != NO_ERROR) { - HILOGE("Received error %{public}d when doing IPC", ret); - return ErrCode(ret); - } - - HILOGI("Successful"); - return reply.ReadInt32(); -} - -ErrCode SvcExtensionProxy::PublishFile(const string &fileName) -{ - HILOGI("Start"); - MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); - - if (!data.WriteString(fileName)) { - BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fileName"); - return ErrCode(EPERM); - } - - MessageParcel reply; - MessageOption option; - int32_t ret = Remote()->SendRequest(IExtension::CMD_PUBLISH_FILE, data, reply, option); - if (ret != NO_ERROR) { - HILOGE("Received error %{public}d when doing IPC", ret); - return ErrCode(ret); - } - - HILOGI("Successful"); - return reply.ReadInt32(); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp deleted file mode 100644 index 286dddbc7..000000000 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/svc_session_manager.h" - -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_json/b_json_entity_ext_manage.h" -#include "b_json/b_json_entity_extension_config.h" -#include "b_resources/b_constants.h" -#include "bundle_mgr_client.h" -#include "filemgmt_libhilog.h" -#include "iservice_registry.h" -#include "module_ipc/service.h" -#include "system_ability_definition.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const -{ - shared_lock lock(lock_); - if (impl_.scenario != scenario) { - throw BError(BError::Codes::SDK_MIXED_SCENARIO); - } - if (impl_.clientToken != clientToken) { - throw BError(BError::Codes::SA_REFUSED_ACT, "Caller mismatched"); - } - HILOGE("Succeed to verify the caller"); -} - -void SvcSessionManager::Active(Impl newImpl) -{ - unique_lock lock(lock_); - const Impl &oldImpl = impl_; - if (oldImpl.clientToken) { - throw BError(BError::Codes::SA_REFUSED_ACT, "Already have an active session"); - } - - if (!newImpl.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - if (newImpl.scenario == IServiceReverse::Scenario::UNDEFINED) { - throw BError(BError::Codes::SA_INVAL_ARG, "No scenario was specified"); - } - - GetBundleExtNames(newImpl.backupExtNameMap); - - InitExtConn(newImpl.backupExtNameMap); - - InitClient(newImpl); - impl_ = newImpl; -} - -void SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) -{ - unique_lock lock(lock_); - if (!impl_.clientToken || !impl_.clientProxy) { - HILOGI("Empty session"); - return; - } - if (!force && (!impl_.clientToken || !impl_.clientProxy)) { - throw BError(BError::Codes::SA_REFUSED_ACT, "Try to deactive an empty session"); - } - auto remoteHeldByProxy = impl_.clientProxy->AsObject(); - if (!force && (remoteInAction != remoteHeldByProxy)) { - throw BError(BError::Codes::SA_INVAL_ARG, "Only the client actived the session can deactive it"); - } - - deathRecipient_ = nullptr; - HILOGI("Succeed to deactive a session. Client token = %{public}u, client proxy = 0x%{private}p", impl_.clientToken, - impl_.clientProxy.GetRefPtr()); - impl_ = {}; - extConnectNum_ = 0; -} - -void SvcSessionManager::VerifyBundleName(string &bundleName) -{ - shared_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - auto asVerify = [&bundleName](const auto &it) { return it.first == bundleName; }; - if (none_of(impl_.backupExtNameMap.begin(), impl_.backupExtNameMap.end(), asVerify)) { - stringstream ss; - ss << "Could not find the " << bundleName << " from current session"; - throw BError(BError::Codes::SA_REFUSED_ACT, ss.str()); - } - HILOGE("Succeed to verify the bundleName"); -} - -sptr SvcSessionManager::GetServiceReverseProxy() -{ - unique_lock lock(lock_); - if (!impl_.clientProxy) { - throw BError(BError::Codes::SA_REFUSED_ACT, "Try to deactive an empty session"); - } - return impl_.clientProxy; -} - -IServiceReverse::Scenario SvcSessionManager::GetScenario() -{ - shared_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - return impl_.scenario; -} - -void SvcSessionManager::GetBundleExtNames(map &backupExtNameMap) -{ - if (backupExtNameMap.empty()) { - throw BError(BError::Codes::SA_INVAL_ARG, "No app was selected"); - } - - auto bms = GetBundleManager(); - if (!bms) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Bms is invalid"); - } - - for (auto &&it : backupExtNameMap) { - AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(it.first, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, - AppExecFwk::Constants::START_USERID)) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get the info of bundle " + it.first); - } - for (auto &&ext : installedBundle.extensionInfos) { - if (ext.type == AppExecFwk::ExtensionAbilityType::BACKUP) { - if (ext.name.empty()) { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to get ext name of bundle " + it.first); - } - vector out; - AppExecFwk::BundleMgrClient client; - if (!client.GetResConfigFile(ext, "ohos.extension.backup", out) || out.size() == 0) { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to get resconfigfile of bundle " + it.first); - } - BJsonCachedEntity cachedEntity(out[0], it.first); - auto cache = cachedEntity.Structuralize(); - if (cache.GetAllowToBackupRestore()) { - it.second.backupExtName = ext.name; - } else { - throw BError(BError::Codes::SA_INVAL_ARG, - "Permission denied to get allowToBackupRestore of bundle " + it.first); - } - } - } - } -} - -bool SvcSessionManager::OnBunleFileReady(const string &bundleName, const string &fileName) -{ - unique_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - - auto it = impl_.backupExtNameMap.find(bundleName); - if (it == impl_.backupExtNameMap.end()) { - stringstream ss; - ss << "Could not find the " << bundleName << " from current session"; - throw BError(BError::Codes::SA_REFUSED_ACT, ss.str()); - } - - // 判断是否结束 通知EXTENTION清理资源 TOOL应用完成备份 - if (impl_.scenario == IServiceReverse::Scenario::RESTORE) { - return true; - } else if (impl_.scenario == IServiceReverse::Scenario::BACKUP) { - if (!fileName.empty() && fileName != BConstants::EXT_BACKUP_MANAGE) { - auto ret = it->second.fileNameInfo.insert(fileName); - if (!ret.second) { - it->second.fileNameInfo.erase(fileName); - } - } else if (fileName.empty()) { - it->second.receExtAppDone = true; - } - if (it->second.receExtManageJson && it->second.fileNameInfo.empty() && it->second.receExtAppDone) { - return true; - } - } - return false; -} - -UniqueFd SvcSessionManager::OnBunleExtManageInfo(const string &bundleName, UniqueFd fd) -{ - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - if (impl_.scenario != IServiceReverse::Scenario::BACKUP) { - throw BError(BError::Codes::SA_INVAL_ARG, "Invalid Scenario"); - } - - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - auto info = cache.GetExtManage(); - - for (auto &fileName : info) { - HILOGE("fileName %{public}s", fileName.data()); - OnBunleFileReady(bundleName, fileName); - } - - unique_lock lock(lock_); - auto it = GetBackupExtNameMap(bundleName); - it->second.receExtManageJson = true; - return move(cachedEntity.GetFd()); -} - -void SvcSessionManager::RemoveExtInfo(const string &bundleName) -{ - HILOGI("Begin"); - unique_lock lock(lock_); - auto it = impl_.backupExtNameMap.find(bundleName); - if (it == impl_.backupExtNameMap.end()) { - return; - } - impl_.backupExtNameMap.erase(it); - extConnectNum_--; -} - -wptr SvcSessionManager::GetExtConnection(const BundleName &bundleName) -{ - HILOGI("Begin"); - shared_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - - auto it = GetBackupExtNameMap(bundleName); - if (!it->second.backUpConnection) { - throw BError(BError::Codes::SA_INVAL_ARG, "Svc backup connection is empty"); - } - - return wptr(it->second.backUpConnection); -} - -void SvcSessionManager::InitExtConn(std::map &backupExtNameMap) -{ - HILOGI("Begin"); - if (backupExtNameMap.empty()) { - throw BError(BError::Codes::SA_INVAL_ARG, "No app was selected"); - } - - for (auto &&it : backupExtNameMap) { - auto callDied = [revPtr {reversePtr_}](const string &&bundleName) { - auto revPtrStrong = revPtr.promote(); - if (!revPtrStrong) { - // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下 - HILOGW("It's curious that the backup sa dies before the backup client"); - return; - } - revPtrStrong->OnBackupExtensionDied(move(bundleName), ESRCH); - }; - - auto callConnDone = [revPtr {reversePtr_}](const string &&bundleName) { - auto revPtrStrong = revPtr.promote(); - if (!revPtrStrong) { - // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下 - HILOGW("It's curious that the backup sa dies before the backup client"); - return; - } - revPtrStrong->ExtConnectDone(move(bundleName)); - }; - - auto backUpConnection = sptr(new SvcBackupConnection(callDied, callConnDone)); - it.second.backUpConnection = backUpConnection; - } -} - -void SvcSessionManager::DumpInfo(const int fd, const std::vector &args) -{ - dprintf(fd, "---------------------backup info--------------------\n"); - dprintf(fd, "Scenario: %d\n", impl_.scenario); -} - -void SvcSessionManager::InitClient(Impl &newImpl) -{ - if (!newImpl.clientProxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Invalid client"); - } - auto remoteObj = newImpl.clientProxy->AsObject(); - if (!remoteObj) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Proxy's remote object can't be nullptr"); - } - - auto callback = [revPtr {reversePtr_}](const wptr &obj) { - HILOGI("Client died. Died remote obj = %{private}p", obj.GetRefPtr()); - - auto revPtrStrong = revPtr.promote(); - if (!revPtrStrong) { - // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下 - HILOGW("It's curious that the backup sa dies before the backup client"); - return; - } - (void)revPtrStrong->StopAll(obj); - }; - deathRecipient_ = sptr(new SvcDeathRecipient(callback)); - remoteObj->AddDeathRecipient(deathRecipient_); - HILOGI( - "Succeed to active a session." - "Client token = %{public}u, client proxy = 0x%{private}p, remote obj = 0x%{private}p", - impl_.clientToken, impl_.clientProxy.GetRefPtr(), remoteObj.GetRefPtr()); -} - -void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &fileName) -{ - HILOGI("Begin"); - unique_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - - auto it = GetBackupExtNameMap(bundleName); - it->second.fileNameInfo.insert(fileName); -} - -std::set SvcSessionManager::GetExtFileNameRequest(const std::string &bundleName) -{ - HILOGI("Begin"); - shared_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - - if (impl_.scenario != IServiceReverse::Scenario::RESTORE) { - throw BError(BError::Codes::SA_INVAL_ARG, "Invalid Scenario"); - } - auto it = GetBackupExtNameMap(bundleName); - return it->second.fileNameInfo; -} - -map::iterator SvcSessionManager::GetBackupExtNameMap(const string &bundleName) -{ - auto it = impl_.backupExtNameMap.find(bundleName); - if (it == impl_.backupExtNameMap.end()) { - stringstream ss; - ss << "Could not find the " << bundleName << " from current session"; - throw BError(BError::Codes::SA_REFUSED_ACT, ss.str()); - } - return it; -} - -bool SvcSessionManager::GetSchedBundleName(string &bundleName) -{ - HILOGI("Begin"); - shared_lock lock(lock_); - if (extConnectNum_ >= BConstants::EXT_CONNECT_MAX_COUNT) { - return false; - } - - for (auto &&it : impl_.backupExtNameMap) { - if (it.second.schedAction == BConstants::ServiceSchedAction::WAIT) { - bundleName = it.first; - return true; - } - } - return false; -} - -BConstants::ServiceSchedAction SvcSessionManager::GetServiceSchedAction(const std::string &bundleName) -{ - HILOGI("Begin"); - shared_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - auto it = GetBackupExtNameMap(bundleName); - return it->second.schedAction; -} - -void SvcSessionManager::SetServiceSchedAction(const string &bundleName, BConstants::ServiceSchedAction action) -{ - HILOGI("Begin"); - unique_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - - auto it = GetBackupExtNameMap(bundleName); - it->second.schedAction = action; - if (it->second.schedAction == BConstants::ServiceSchedAction::START) { - extConnectNum_++; - } -} - -string SvcSessionManager::GetBackupExtName(const string &bundleName) -{ - HILOGI("Begin"); - shared_lock lock(lock_); - if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); - } - auto it = GetBackupExtNameMap(bundleName); - return it->second.backupExtName; -} - -sptr SvcSessionManager::GetBundleManager() -{ - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - HILOGI("SystemAbilityManager is nullptr."); - return nullptr; - } - - auto bundleObj = saMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (bundleObj == nullptr) { - HILOGI("Failed to get bundle manager service."); - return nullptr; - } - - return iface_cast(bundleObj); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp deleted file mode 100644 index 9257b89f6..000000000 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_sched/sched_scheduler.h" - -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" -#include "module_ipc/service.h" -#include "module_ipc/svc_session_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void SchedScheduler::Sched(string bundleName) -{ - if (bundleName == "") { - if (!sessionPtr_->GetSchedBundleName(bundleName)) { - return; - } - BConstants::ServiceSchedAction action = sessionPtr_->GetServiceSchedAction(bundleName); - if (action == BConstants::ServiceSchedAction::WAIT) { - sessionPtr_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::START); - } - } - HILOGE("Sched bundleName %{public}s", bundleName.data()); - auto callStart = [schedPtr {wptr(this)}, bundleName]() { - try { - auto ptr = schedPtr.promote(); - ptr->ExecutingQueueTasks(bundleName); - } catch (const BError &e) { - HILOGE("%{public}s", e.what()); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - } catch (...) { - HILOGE(""); - } - }; - threadPool_.AddTask(callStart); -} - -void SchedScheduler::ExecutingQueueTasks(const string &bundleName) -{ - HILOGE("start"); - BConstants::ServiceSchedAction action = sessionPtr_->GetServiceSchedAction(bundleName); - if (action == BConstants::ServiceSchedAction::START) { - // 注册启动定时器 - auto callStart = [reversePtr {reversePtr_}, bundleName]() { - HILOGE("Extension connect failed = %{public}s", bundleName.data()); - auto ptr = reversePtr.promote(); - if (ptr) { - ptr->ExtConnectFailed(bundleName, EPERM); - } - }; - auto iTime = extTime_.Register(callStart, BConstants::EXT_CONNECT_MAX_TIME); - unique_lock lock(lock_); - bundleTimeVec_.emplace_back(make_tuple(bundleName, iTime)); - lock.unlock(); - // 启动extension - reversePtr_->LaunchBackupExtension(bundleName); - } else if (action == BConstants::ServiceSchedAction::RUNNING) { - unique_lock lock(lock_); - auto iter = find_if(bundleTimeVec_.begin(), bundleTimeVec_.end(), [&bundleName](auto &obj) { - auto &[bName, iTime] = obj; - return bName == bundleName; - }); - if (iter == bundleTimeVec_.end()) { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to find timer"); - } - auto &[bName, iTime] = *iter; - // 移除启动定时器 当前逻辑无启动成功后的ext心跳检测 - extTime_.Unregister(iTime); - lock.unlock(); - // 开始执行备份恢复流程 - reversePtr_->ExtStart(bundleName); - } -} - -void SchedScheduler::RemoveExtConn(const string &bundleName) -{ - unique_lock lock(lock_); - auto iter = find_if(bundleTimeVec_.begin(), bundleTimeVec_.end(), [&bundleName](auto &obj) { - auto &[bName, iTime] = obj; - return bName == bundleName; - }); - if (iter != bundleTimeVec_.end()) { - auto &[bName, iTime] = *iter; - HILOGE("bundleName = %{public}s , iTime = %{public}d", bName.data(), iTime); - extTime_.Unregister(iTime); - bundleTimeVec_.erase(iter); - } -} -}; // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/accesstoken/accesstoken_kit_mock.cpp b/tests/mock/accesstoken/accesstoken_kit_mock.cpp deleted file mode 100644 index 153183770..000000000 --- a/tests/mock/accesstoken/accesstoken_kit_mock.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "accesstoken_kit.h" - -namespace OHOS::Security::AccessToken { -ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) -{ - return TOKEN_HAP; -} - -int AccessTokenKit::GetHapTokenInfo(AccessTokenID callerToken, HapTokenInfo &hapTokenInfoRes) -{ - hapTokenInfoRes.bundleName = "com.example.app2backup"; - return 0; -} - -int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string &permissionName) -{ - return 0; -} -} // namespace OHOS::Security::AccessToken diff --git a/tests/mock/affwk/service_registry_mock.cpp b/tests/mock/affwk/service_registry_mock.cpp deleted file mode 100644 index 9ec473467..000000000 --- a/tests/mock/affwk/service_registry_mock.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "iservice_registry.h" -#include "mock_bundle_manager.h" -#include "system_ability_definition.h" -#include "system_ability_manager_proxy.h" - -namespace OHOS { -static sptr g_appMgrService = nullptr; - -SystemAbilityManagerClient &SystemAbilityManagerClient::GetInstance() -{ - static auto instance = new SystemAbilityManagerClient(); - return *instance; -} - -sptr SystemAbilityManagerProxy::GetSystemAbility(int32_t systemAbilityId) -{ - sptr remote = nullptr; - switch (systemAbilityId) { - case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: - if (!g_appMgrService) { - GTEST_LOG_(INFO) << "GetSystemAbility(" << systemAbilityId << "): return Mock"; - g_appMgrService = new AppExecFwk::BundleMgrStub(); - } - remote = g_appMgrService; - break; - default: - GTEST_LOG_(INFO) << "This service is not dummy!!!!" << systemAbilityId; - break; - } - return remote; -} - -sptr SystemAbilityManagerClient::GetSystemAbilityManager() -{ - std::lock_guard lock(systemAbilityManagerLock_); - if (systemAbilityManager_ != nullptr) { - return systemAbilityManager_; - } - - systemAbilityManager_ = new SystemAbilityManagerProxy(nullptr); - return systemAbilityManager_; -} - -sptr SystemAbilityManagerProxy::GetSystemAbility(int32_t systemAbilityId, const std::string &deviceId) -{ - return GetSystemAbility(systemAbilityId); -} -} // namespace OHOS \ No newline at end of file diff --git a/tests/mock/b_filesystem/b_file_mock.cpp b/tests/mock/b_filesystem/b_file_mock.cpp deleted file mode 100644 index d3561215a..000000000 --- a/tests/mock/b_filesystem/b_file_mock.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_filesystem/b_file.h" - -#include - -#include -#include -#include - -namespace OHOS::FileManagement::Backup { -using namespace std; - -unique_ptr BFile::ReadFile(const UniqueFd &fd) -{ - if (lseek(fd, 0, SEEK_SET) == -1) { - GTEST_LOG_(INFO) << "BFile::ReadFile lseek error " << errno; - return make_unique(1); - } - - struct stat stat = {}; - if (fstat(fd, &stat) == -1) { - GTEST_LOG_(INFO) << "BFile::ReadFile fstat error " << errno; - return make_unique(1); - } - off_t fileSize = stat.st_size; - if (fileSize == 0) { - GTEST_LOG_(INFO) << "BFile::ReadFile fileSize error " << fileSize; - return make_unique(1); - } - - auto buf = make_unique(fileSize + 1); - if (read(fd, buf.get(), fileSize) == -1) { - GTEST_LOG_(INFO) << "BFile::ReadFile read error " << errno; - } - return buf; -} - -void BFile::SendFile(int outFd, int inFd) -{ - if (outFd <= 0 || inFd <= 0) { - return; - } - off_t offset = 0; - long ret = 0; - if (lseek(outFd, 0, SEEK_SET) == -1) { - GTEST_LOG_(INFO) << "BFile::SendFile lseek1 error " << errno; - return; - } - if (lseek(inFd, 0, SEEK_SET) == -1) { - GTEST_LOG_(INFO) << "BFile::SendFile lseek2 error " << errno; - return; - } - struct stat stat = {}; - if (fstat(inFd, &stat) == -1) { - GTEST_LOG_(INFO) << "BFile::SendFile fstat error " << errno; - return; - } - while ((ret = sendfile(outFd, inFd, &offset, stat.st_size)) > 0) { - }; - - if (ret == -1) { - GTEST_LOG_(INFO) << "BFile::SendFile ret error " << ret; - } -} - -void BFile::Write(const UniqueFd &fd, const string &str) {} - -bool BFile::CopyFile(const string &from, const string &to) -{ - return true; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/b_process/b_process/b_multiuser.h b/tests/mock/b_process/b_process/b_multiuser.h deleted file mode 100644 index 391260dcf..000000000 --- a/tests/mock/b_process/b_process/b_multiuser.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_MULTIUSER_MOCK_H -#define OHOS_FILEMGMT_BACKUP_B_MULTIUSER_MOCK_H - -#include "b_resources/b_constants.h" - -#include - -namespace OHOS::FileManagement::Backup { -class BMultiuser { -public: - struct UidReadOut { - int userId; - int appId; - }; - -public: - static UidReadOut ParseUid(int uid) - { - return UidReadOut { - .userId = BConstants::DEFAULT_USER_ID, - .appId = BConstants::DEFAULT_USER_ID, - }; - } -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_MULTIUSER_MOCK_H \ No newline at end of file diff --git a/tests/mock/b_process/b_process_mock.cpp b/tests/mock/b_process/b_process_mock.cpp deleted file mode 100644 index 89b05d74e..000000000 --- a/tests/mock/b_process/b_process_mock.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_process/b_process.h" - -#include -#include - -namespace OHOS::FileManagement::Backup { -using namespace std; - -tuple BProcess::ExecuteCmd(vector argvSv, function DetectFatalLog) -{ - GTEST_LOG_(INFO) << "BProcess ExecuteCmd Begin"; - DetectFatalLog("test"); - DetectFatalLog("EOF"); - GTEST_LOG_(INFO) << "BProcess ExecuteCmd End"; - return {false, 0}; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/b_tarball/b_tarball_cmdline_mock.cpp b/tests/mock/b_tarball/b_tarball_cmdline_mock.cpp deleted file mode 100644 index a323ffb25..000000000 --- a/tests/mock/b_tarball/b_tarball_cmdline_mock.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_tarball/b_tarball_cmdline.h" - -#include -#include - -#include - -#include -#include - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void BTarballCmdline::Tar(string_view root, vector includes, vector excludes) -{ - GTEST_LOG_(INFO) << "BTarballCmdline Tar " << root; -} - -void BTarballCmdline::Untar(string_view root) -{ - GTEST_LOG_(INFO) << "BTarballCmdline Untar " << root; -} - -BTarballCmdline::BTarballCmdline(string_view tarballDir, string_view tarballName) - : tarballDir_(tarballDir), tarballName_(tarballName) -{ - tarballPath_ = tarballDir_ + "/" + tarballName_; -} -} // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/backup_kit_inner/b_session_backup_mock.cpp b/tests/mock/backup_kit_inner/b_session_backup_mock.cpp deleted file mode 100644 index a5b65ccb4..000000000 --- a/tests/mock/backup_kit_inner/b_session_backup_mock.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_session_backup.h" - -#include -#include -#include - -#include -#include - -#include "b_error/b_error.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -namespace { -static BSessionBackup::Callbacks callbacks_ = {}; -} // namespace - -BSessionBackup::~BSessionBackup() {} - -unique_ptr BSessionBackup::Init(UniqueFd remoteCap, - vector bundlesToBackup, - Callbacks callbacks) -{ - try { - callbacks_ = callbacks; - auto backup = make_unique(); - return backup; - } catch (const exception &e) { - return nullptr; - } - return nullptr; -} - -void BSessionBackup::RegisterBackupServiceDied(function functor) {} - -ErrCode BSessionBackup::Start() -{ - callbacks_.onBundleStarted(0, "com.example.app2backup"); - - BFileInfo bFileInfo("com.example.app2backup", "manage.json", 0); - TestManager tm("BSessionBackupMock_GetFd_0100"); - string fileManagePath = tm.GetRootDirCurTest().append("manage.json"); - SaveStringToFile(fileManagePath, R"([{"fileName": "1.tar"}])"); - UniqueFd fd(open(fileManagePath.data(), O_RDWR, S_IRWXU)); - GTEST_LOG_(INFO) << "callbacks_::onFileReady manage.json"; - callbacks_.onFileReady(bFileInfo, move(fd)); - - string filePath = tm.GetRootDirCurTest().append("1.tar"); - UniqueFd fdTar(open(filePath.data(), O_RDONLY | O_CREAT, S_IRWXU)); - bFileInfo.fileName = "1.tar"; - GTEST_LOG_(INFO) << "callbacks_::onFileReady 1.tar"; - callbacks_.onFileReady(bFileInfo, move(fdTar)); - - callbacks_.onBundleFinished(0, "com.example.app2backup"); - - callbacks_.onAllBundlesFinished(0); - callbacks_.onBundleStarted(1, "com.example.app2backup"); - callbacks_.onBundleFinished(1, "com.example.app2backup"); - callbacks_.onAllBundlesFinished(1); - - string filePathTwo = tm.GetRootDirCurTest().append("1.tar"); - UniqueFd fdFile(open(filePathTwo.data(), O_RDONLY | O_CREAT, S_IRWXU)); - GTEST_LOG_(INFO) << "callbacks_::onFileReady 1.tar"; - callbacks_.onFileReady(bFileInfo, move(fdFile)); - - callbacks_.onBackupServiceDied(); - return BError(BError::Codes::OK); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/b_session_restore_mock.cpp b/tests/mock/backup_kit_inner/b_session_restore_mock.cpp deleted file mode 100644 index 3cfad611f..000000000 --- a/tests/mock/backup_kit_inner/b_session_restore_mock.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_session_restore.h" - -#include -#include -#include - -#include -#include - -#include "b_error/b_error.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -namespace { -static BSessionRestore::Callbacks callbacks_ = {}; -static vector bundlesToRestore_ = {}; -} // namespace - -BSessionRestore::~BSessionRestore() {} - -unique_ptr BSessionRestore::Init(vector bundlesToRestore, Callbacks callbacks) -{ - try { - callbacks_ = move(callbacks); - bundlesToRestore_ = move(bundlesToRestore); - auto restore = make_unique(); - return restore; - } catch (const exception &e) { - return nullptr; - } - return nullptr; -} - -UniqueFd BSessionRestore::GetLocalCapabilities() -{ - string bundleName = "test"; - auto iter = find_if(bundlesToRestore_.begin(), bundlesToRestore_.end(), [&bundleName](auto &obj) { - const auto &bName = obj; - return bName == bundleName; - }); - if (iter != bundlesToRestore_.end()) { - return UniqueFd(-1); - } - TestManager tm("BSessionRestoreMock_GetFd_0100"); - string filePath = tm.GetRootDirCurTest().append("tmp"); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - return fd; -} - -ErrCode BSessionRestore::PublishFile(BFileInfo fileInfo) -{ - return BError(BError::Codes::OK); -} - -ErrCode BSessionRestore::Start() -{ - callbacks_.onBundleStarted(0, "com.example.app2backup"); - - BFileInfo bFileInfo("com.example.app2backup", "1.tar", 0); - TestManager tm("BSessionRestoreMock_GetFd_0100"); - string filePath = tm.GetRootDirCurTest().append("1.tar"); - UniqueFd fd(open(filePath.data(), O_RDWR | O_CREAT, S_IRWXU)); - GTEST_LOG_(INFO) << "callbacks_::onFileReady 1.tar"; - callbacks_.onFileReady(bFileInfo, move(fd)); - - string fileManagePath = tm.GetRootDirCurTest().append("manage.json"); - UniqueFd fdManage(open(fileManagePath.data(), O_RDWR | O_CREAT, S_IRWXU)); - bFileInfo.fileName = "manage.json"; - GTEST_LOG_(INFO) << "callbacks_::onFileReady manage.json"; - callbacks_.onFileReady(bFileInfo, move(fdManage)); - - callbacks_.onBundleFinished(0, "com.example.app2backup"); - - callbacks_.onAllBundlesFinished(0); - callbacks_.onBundleStarted(1, "com.example.app2backup"); - callbacks_.onBundleFinished(1, "com.example.app2backup"); - callbacks_.onAllBundlesFinished(1); - - callbacks_.onBackupServiceDied(); - return BError(BError::Codes::OK); -} - -ErrCode BSessionRestore::GetExtFileName(string &bundleName, string &fileName) -{ - return BError(BError::Codes::OK); -} - -void BSessionRestore::RegisterBackupServiceDied(function functor) {} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/service_proxy_mock.cpp b/tests/mock/backup_kit_inner/service_proxy_mock.cpp deleted file mode 100644 index 5c4bdc226..000000000 --- a/tests/mock/backup_kit_inner/service_proxy_mock.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "service_proxy.h" - -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_resources/b_constants.h" -#include "iremote_object_mock.h" -#include "test_manager.h" -#include "utils_mock_global_variable.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -int32_t ServiceProxy::InitRestoreSession(sptr remote, const vector &bundleNames) -{ - if (!GetMockInitBackupOrRestoreSession()) { - return 1; - } - return 0; -} - -int32_t ServiceProxy::InitBackupSession(sptr remote, - UniqueFd fd, - const vector &bundleNames) -{ - if (!GetMockInitBackupOrRestoreSession()) { - return 1; - } - return 0; -} - -ErrCode ServiceProxy::Start() -{ - return BError(BError::Codes::OK); -} - -UniqueFd ServiceProxy::GetLocalCapabilities() -{ - TestManager tm("ServiceProxyMock_GetFd_0100"); - string filePath = tm.GetRootDirCurTest().append("tmp"); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - return fd; -} - -ErrCode ServiceProxy::PublishFile(const BFileInfo &fileInfo) -{ - return BError(BError::Codes::OK); -} - -ErrCode ServiceProxy::AppFileReady(const string &fileName, UniqueFd fd) -{ - return BError(BError::Codes::OK); -} - -ErrCode ServiceProxy::AppDone(ErrCode errCode) -{ - return BError(BError::Codes::OK); -} - -ErrCode ServiceProxy::GetExtFileName(string &bundleName, string &fileName) -{ - return BError(BError::Codes::OK); -} - -sptr ServiceProxy::GetInstance() -{ - if (!GetMockGetInstance()) { - return nullptr; - } - - if (!GetMockLoadSystemAbility()) { - serviceProxy_ = sptr(new ServiceProxy(nullptr)); - } else { - sptr object = new MockIRemoteObject(); - serviceProxy_ = sptr(new ServiceProxy(object)); - } - return serviceProxy_; -} - -void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, - const OHOS::sptr &remoteObject) -{ - return; -} - -void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) -{ - return; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/bundle_manager/include/mock_bundle_manager.h b/tests/mock/bundle_manager/include/mock_bundle_manager.h deleted file mode 100644 index b50908b42..000000000 --- a/tests/mock/bundle_manager/include/mock_bundle_manager.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MOCK_BUNDLE_MANAGER_H -#define MOCK_BUNDLE_MANAGER_H - -#include -#include - -#include "ability_info.h" -#include "application_info.h" -#include "bundlemgr/bundle_mgr_interface.h" -#include "iremote_proxy.h" -#include "iremote_stub.h" - -namespace OHOS { -namespace AppExecFwk { -class BundleMgrProxy : public IRemoteProxy { -public: - explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) {} - virtual ~BundleMgrProxy() {} - - bool GetBundleInfo(const std::string &bundleName, - const BundleFlag flag, - BundleInfo &bundleInfo, - int32_t userId) override; -}; - -class BundleMgrStub : public IRemoteStub { -public: - BundleMgrStub() {}; - virtual ~BundleMgrStub() {} - virtual int OnRemoteRequest(uint32_t code, - MessageParcel &data, - MessageParcel &reply, - MessageOption &option) override; - - virtual bool GetBundleInfo(const std::string &bundleName, - const BundleFlag flag, - BundleInfo &bundleInfo, - int32_t userId = Constants::UNSPECIFIED_USERID) override; - - virtual bool GetBundleInfo(const std::string &bundleName, - int32_t flags, - BundleInfo &bundleInfo, - int32_t userId = Constants::UNSPECIFIED_USERID) override; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // MOCK_BUNDLE_MANAGER_H \ No newline at end of file diff --git a/tests/mock/bundle_manager/src/mock_bundle_manager.cpp b/tests/mock/bundle_manager/src/mock_bundle_manager.cpp deleted file mode 100644 index 4b397ee2a..000000000 --- a/tests/mock/bundle_manager/src/mock_bundle_manager.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "mock_bundle_manager.h" - -#include -#include -#include - -#include "ability_config.h" -#include "ability_info.h" -#include "application_info.h" -#include "bundle_mgr_client.h" - -namespace OHOS { -namespace AppExecFwk { -using namespace std; -using namespace OHOS::AAFwk; - -bool BundleMgrProxy::GetBundleInfo(const string &bundleName, - const BundleFlag flag, - BundleInfo &bundleInfo, - int32_t userId) -{ - GTEST_LOG_(INFO) << "GetBundleInfo is ok"; - ExtensionAbilityInfo info; - info.type = AppExecFwk::ExtensionAbilityType::BACKUP; - info.name = "com.example.app2backup"; - bundleInfo.extensionInfos.push_back(info); - return true; -} - -int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - return 0; -} - -bool BundleMgrStub::GetBundleInfo(const string &bundleName, - const BundleFlag flag, - BundleInfo &bundleInfo, - int32_t userId) -{ - GTEST_LOG_(INFO) << "GetBundleInfo is ok"; - ExtensionAbilityInfo info; - info.type = AppExecFwk::ExtensionAbilityType::BACKUP; - info.name = "com.example.app2backup"; - bundleInfo.extensionInfos.push_back(info); - return true; -} - -bool BundleMgrStub::GetBundleInfo(const string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId) -{ - GTEST_LOG_(INFO) << "GetBundleInfo is ok"; - ExtensionAbilityInfo info; - info.type = AppExecFwk::ExtensionAbilityType::BACKUP; - info.name = "com.example.app2backup"; - bundleInfo.extensionInfos.push_back(info); - return true; -} - -BundleMgrClient::BundleMgrClient() {} - -BundleMgrClient::~BundleMgrClient() {} - -bool BundleMgrClient::GetResConfigFile(const ExtensionAbilityInfo &extensionInfo, - const string &metadataName, - vector &profileInfos) const -{ - GTEST_LOG_(INFO) << "GetResConfigFile is ok"; - string str = "{\"allowToBackupRestore\":true}"; - profileInfos.push_back(str); - return true; -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp deleted file mode 100644 index c324bd3fe..000000000 --- a/tests/mock/module_ipc/service_mock.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/service.h" - -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_resources/b_constants.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void Service::OnStart() {} - -void Service::OnStop() {} - -UniqueFd Service::GetLocalCapabilities() -{ - return UniqueFd(-1); -} - -void Service::StopAll(const wptr &obj, bool force) {} - -string Service::VerifyCallerAndGetCallerName() -{ - return ""; -} - -ErrCode Service::InitRestoreSession(sptr remote, const vector &bundleNames) -{ - return BError(BError::Codes::OK); -} - -ErrCode Service::InitBackupSession(sptr remote, UniqueFd fd, const vector &bundleNames) -{ - return BError(BError::Codes::OK); -} - -ErrCode Service::Start() -{ - return BError(BError::Codes::OK); -} - -ErrCode Service::PublishFile(const BFileInfo &fileInfo) -{ - return BError(BError::Codes::OK); -} - -ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd) -{ - return BError(BError::Codes::OK); -} - -ErrCode Service::AppDone(ErrCode errCode) -{ - return BError(BError::Codes::OK); -} - -ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) -{ - return BError(BError::Codes::OK); -} - -ErrCode Service::GetExtFileName(string &bundleName, string &fileName) -{ - return BError(BError::Codes::OK); -} - -void Service::OnBackupExtensionDied(const string &&bundleName, ErrCode ret) {} - -void Service::ExtStart(const string &bundleName) {} - -int Service::Dump(int fd, const vector &args) -{ - return 0; -} - -void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) -{ - GTEST_LOG_(INFO) << "ExtConnectFailed is OK"; -} - -void Service::ExtConnectDone(string bundleName) {} - -void Service::ClearSessionAndSchedInfo(const string &bundleName) {} - -void Service::VerifyCaller() {} - -void Service::VerifyCaller(IServiceReverse::Scenario scenario) {} -} // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp b/tests/mock/module_ipc/service_reverse_proxy_mock.cpp deleted file mode 100644 index 0f98e5e2e..000000000 --- a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/service_reverse_proxy.h" - -#include "b_error/b_error.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void ServiceReverseProxy::BackupOnFileReady(string bundleName, string fileName, int fd) {} - -void ServiceReverseProxy::BackupOnBundleStarted(int32_t errCode, string bundleName) {} - -void ServiceReverseProxy::BackupOnBundleFinished(int32_t errCode, string bundleName) {} - -void ServiceReverseProxy::BackupOnAllBundlesFinished(int32_t errCode) {} - -void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName) {} - -void ServiceReverseProxy::RestoreOnBundleFinished(int32_t errCode, string bundleName) {} - -void ServiceReverseProxy::RestoreOnAllBundlesFinished(int32_t errCode) {} - -void ServiceReverseProxy::RestoreOnFileReady(string bundleName, string fileName, int fd) {} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_ipc/service_stub_mock.cpp b/tests/mock/module_ipc/service_stub_mock.cpp deleted file mode 100644 index 313a9d2e2..000000000 --- a/tests/mock/module_ipc/service_stub_mock.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/service_stub.h" - -#include - -#include "b_error/b_error.h" -#include "module_ipc/service_reverse_proxy.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -ServiceStub::ServiceStub() -{ - opToInterfaceMap_[SERVICE_CMD_INIT_RESTORE_SESSION] = &ServiceStub::CmdInitRestoreSession; - opToInterfaceMap_[SERVICE_CMD_INIT_BACKUP_SESSION] = &ServiceStub::CmdInitBackupSession; - opToInterfaceMap_[SERVICE_CMD_GET_LOCAL_CAPABILITIES] = &ServiceStub::CmdGetLocalCapabilities; - opToInterfaceMap_[SERVICE_CMD_PUBLISH_FILE] = &ServiceStub::CmdPublishFile; - opToInterfaceMap_[SERVICE_CMD_APP_FILE_READY] = &ServiceStub::CmdAppFileReady; - opToInterfaceMap_[SERVICE_CMD_APP_DONE] = &ServiceStub::CmdAppDone; - opToInterfaceMap_[SERVICE_CMD_START] = &ServiceStub::CmdStart; - opToInterfaceMap_[SERVICE_CMD_GET_EXT_FILE_NAME] = &ServiceStub::CmdGetExtFileName; -} - -int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - auto interfaceIndex = opToInterfaceMap_.find(code); - if (interfaceIndex == opToInterfaceMap_.end() || !interfaceIndex->second) { - return BError(BError::Codes::OK); - } - - const std::u16string descriptor = ServiceStub::GetDescriptor(); - const std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - return BError(BError::Codes::OK); - } - return (this->*(interfaceIndex->second))(data, reply); -} - -int32_t ServiceStub::CmdInitRestoreSession(MessageParcel &data, MessageParcel &reply) -{ - auto remote = data.ReadRemoteObject(); - auto iremote = iface_cast(remote); - - std::vector bundleNames; - data.ReadStringVector(&bundleNames); - int32_t res = InitRestoreSession(iremote, bundleNames); - reply.WriteInt32(res); - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &reply) -{ - auto remote = data.ReadRemoteObject(); - auto iremote = iface_cast(remote); - - UniqueFd fd(data.ReadFileDescriptor()); - - std::vector bundleNames; - data.ReadStringVector(&bundleNames); - - int res = InitBackupSession(iremote, move(fd), bundleNames); - reply.WriteInt32(res); - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdStart(MessageParcel &data, MessageParcel &reply) -{ - int res = Start(); - reply.WriteInt32(res); - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdGetLocalCapabilities(MessageParcel &data, MessageParcel &reply) -{ - UniqueFd fd(GetLocalCapabilities()); - reply.WriteFileDescriptor(fd); - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdPublishFile(MessageParcel &data, MessageParcel &reply) -{ - unique_ptr fileInfo(data.ReadParcelable()); - int res = PublishFile(*fileInfo); - reply.WriteInt32(res); - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdAppFileReady(MessageParcel &data, MessageParcel &reply) -{ - string fileName; - data.ReadString(fileName); - UniqueFd fd(data.ReadFileDescriptor()); - int res = AppFileReady(fileName, move(fd)); - reply.WriteInt32(res); - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdAppDone(MessageParcel &data, MessageParcel &reply) -{ - bool success; - data.ReadBool(success); - int res = AppDone(success); - reply.WriteInt32(res); - return BError(BError::Codes::OK); -} - -int32_t ServiceStub::CmdGetExtFileName(MessageParcel &data, MessageParcel &reply) -{ - string bundleName; - data.ReadString(bundleName); - string fileName; - data.ReadString(fileName); - - return GetExtFileName(bundleName, fileName); -} -} // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/svc_backup_connection_mock.cpp b/tests/mock/module_ipc/svc_backup_connection_mock.cpp deleted file mode 100644 index f08dd4960..000000000 --- a/tests/mock/module_ipc/svc_backup_connection_mock.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/svc_backup_connection.h" - -#include - -#include "module_ipc/svc_extension_proxy.h" -#include "module_ipc/svc_session_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -namespace { -static bool g_bExtAbilityConnected = false; -} - -void SvcBackupConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &element, - const sptr &remoteObject, - int resultCode) -{ - isConnected_.store(true); - backupProxy_ = iface_cast(remoteObject); - string bundleName = ""; - callConnDone_(move(bundleName)); -} - -void SvcBackupConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) -{ - backupProxy_ = nullptr; - isConnected_.store(false); - string bundleName = ""; - callDied_(move(bundleName)); -} - -ErrCode SvcBackupConnection::ConnectBackupExtAbility(AAFwk::Want &want) -{ - return 0; -} - -ErrCode SvcBackupConnection::DisconnectBackupExtAbility() -{ - return 0; -} - -bool SvcBackupConnection::IsExtAbilityConnected() -{ - bool bFlag = g_bExtAbilityConnected; - g_bExtAbilityConnected = !bFlag; - return bFlag; -} - -sptr SvcBackupConnection::GetBackupExtProxy() -{ - return backupProxy_; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp deleted file mode 100644 index 37b21cb83..000000000 --- a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/svc_extension_proxy.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -UniqueFd SvcExtensionProxy::GetFileHandle(const string &fileName) -{ - return UniqueFd(-1); -} - -ErrCode SvcExtensionProxy::HandleClear() -{ - return 0; -} - -ErrCode SvcExtensionProxy::HandleBackup() -{ - return 0; -} - -ErrCode SvcExtensionProxy::PublishFile(const string &fileName) -{ - return 0; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp deleted file mode 100644 index e5105627c..000000000 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_ipc/svc_session_manager.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "b_resources/b_constants.h" -#include "ext_extension_mock.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -namespace { -constexpr int SCHED_NUM = 1; -constexpr int FILE_NUM = 2; -static int32_t g_nFileReadyNum = 0; -} // namespace - -void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const -{ - GTEST_LOG_(INFO) << "VerifyCallerAndScenario"; -} - -void SvcSessionManager::Active(Impl newImpl) -{ - GTEST_LOG_(INFO) << "Active"; - extConnectNum_ = 0; - impl_ = newImpl; -} - -void SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) -{ - GTEST_LOG_(INFO) << "Deactive"; -} - -void SvcSessionManager::VerifyBundleName(string &bundleName) -{ - GTEST_LOG_(INFO) << "VerifyBundleName " << bundleName; -} - -sptr SvcSessionManager::GetServiceReverseProxy() -{ - GTEST_LOG_(INFO) << "GetServiceReverseProxy"; - return impl_.clientProxy; -} - -IServiceReverse::Scenario SvcSessionManager::GetScenario() -{ - GTEST_LOG_(INFO) << "GetScenario"; - return impl_.scenario; -} - -void SvcSessionManager::GetBundleExtNames(map &backupExtNameMap) -{ - GTEST_LOG_(INFO) << "GetBundleExtNames"; -} - -bool SvcSessionManager::OnBunleFileReady(const string &bundleName, const string &fileName) -{ - GTEST_LOG_(INFO) << "OnBunleFileReady"; - g_nFileReadyNum++; - if (g_nFileReadyNum % FILE_NUM == SCHED_NUM) { - GTEST_LOG_(INFO) << "OnBunleFileReady is true"; - return true; - } - GTEST_LOG_(INFO) << "OnBunleFileReady is false"; - return false; -} - -UniqueFd SvcSessionManager::OnBunleExtManageInfo(const string &bundleName, UniqueFd fd) -{ - GTEST_LOG_(INFO) << "OnBunleExtManageInfo"; - return UniqueFd(-1); -} - -void SvcSessionManager::RemoveExtInfo(const string &bundleName) -{ - GTEST_LOG_(INFO) << "RemoveExtInfo"; -} - -wptr SvcSessionManager::GetExtConnection(const BundleName &bundleName) -{ - GTEST_LOG_(INFO) << "GetExtConnection"; - auto it = impl_.backupExtNameMap.find(bundleName); - if (it == impl_.backupExtNameMap.end()) { - return nullptr; - } - if (!it->second.backUpConnection) { - auto callDied = [](const string &&bundleName) {}; - auto callConnDone = [](const string &&bundleName) {}; - it->second.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnDone)); - sptr mock = sptr(new BackupExtExtensionMock()); - it->second.backUpConnection->OnAbilityConnectDone({}, mock->AsObject(), 0); - } - return wptr(it->second.backUpConnection); -} - -void SvcSessionManager::InitExtConn(std::map &backupExtNameMap) -{ - GTEST_LOG_(INFO) << "InitExtConn"; -} - -void SvcSessionManager::DumpInfo(const int fd, const std::vector &args) -{ - GTEST_LOG_(INFO) << "DumpInfo"; -} - -void SvcSessionManager::InitClient(Impl &newImpl) -{ - GTEST_LOG_(INFO) << "InitClient"; -} - -void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &fileName) -{ - GTEST_LOG_(INFO) << "SetExtFileNameRequest"; -} - -std::set SvcSessionManager::GetExtFileNameRequest(const std::string &bundleName) -{ - GTEST_LOG_(INFO) << "GetExtFileNameRequest"; - std::set fileNameInfo; - fileNameInfo.insert("testName"); - fileNameInfo.insert("fileName"); - return fileNameInfo; -} - -map::iterator SvcSessionManager::GetBackupExtNameMap(const string &bundleName) -{ - GTEST_LOG_(INFO) << "GetBackupExtNameMap"; - auto it = impl_.backupExtNameMap.find(bundleName); - return it; -} - -bool SvcSessionManager::GetSchedBundleName(string &bundleName) -{ - if (extConnectNum_ == 0) { - GTEST_LOG_(INFO) << "GetSchedBundleName is zero"; - extConnectNum_++; - return false; - } else if (extConnectNum_ == SCHED_NUM || extConnectNum_ == (SCHED_NUM + 1)) { - GTEST_LOG_(INFO) << "GetSchedBundleName is one two"; - bundleName = "com.example.app2backup"; - extConnectNum_++; - return true; - } - - auto it = impl_.backupExtNameMap.find(bundleName); - if (it == impl_.backupExtNameMap.end()) { - return false; - } - it->second.backupExtName = bundleName; - GTEST_LOG_(INFO) << "GetSchedBundleName is " << it->second.backupExtName; - return true; -} - -BConstants::ServiceSchedAction SvcSessionManager::GetServiceSchedAction(const std::string &bundleName) -{ - auto it = impl_.backupExtNameMap.find(bundleName); - if (it == impl_.backupExtNameMap.end()) { - return BConstants::ServiceSchedAction::WAIT; - } - GTEST_LOG_(INFO) << "GetServiceSchedAction is " << it->second.schedAction; - return it->second.schedAction; -} - -void SvcSessionManager::SetServiceSchedAction(const string &bundleName, BConstants::ServiceSchedAction action) -{ - auto it = impl_.backupExtNameMap.find(bundleName); - if (it == impl_.backupExtNameMap.end()) { - return; - } - it->second.schedAction = action; -} - -string SvcSessionManager::GetBackupExtName(const string &bundleName) -{ - GTEST_LOG_(INFO) << "GetBackupExtName " << bundleName; - return ""; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_sched/sched_scheduler_mock.cpp b/tests/mock/module_sched/sched_scheduler_mock.cpp deleted file mode 100644 index 88c947a75..000000000 --- a/tests/mock/module_sched/sched_scheduler_mock.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "module_sched/sched_scheduler.h" - -#include "module_ipc/service.h" -#include "module_ipc/svc_session_manager.h" - -#include -#include - -namespace OHOS::FileManagement::Backup { -using namespace std; - -void SchedScheduler::Sched(string bundleName) {} - -void SchedScheduler::ExecutingQueueTasks(const string &bundleName) {} - -void SchedScheduler::RemoveExtConn(const string &bundleName) {} -}; // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/parameter/include/parameter.h b/tests/mock/parameter/include/parameter.h deleted file mode 100644 index 48b7905a6..000000000 --- a/tests/mock/parameter/include/parameter.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MOCK_OHOS_BACKUP_PARAMETER_H -#define MOCK_OHOS_BACKUP_PARAMETER_H - -#include -#include - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif /* __cplusplus */ - -void SetMockParameter(bool para); -bool GetMockParameter(void); - -uint32_t FindParameter(const char *key); -int GetParameterValue(uint32_t handle, char *value, uint32_t len); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif /* __cplusplus */ - -#endif // MOCK_OHOS_BACKUP_PARAMETER_H \ No newline at end of file diff --git a/tests/mock/parameter/src/parameter.c b/tests/mock/parameter/src/parameter.c deleted file mode 100644 index 13f9104cc..000000000 --- a/tests/mock/parameter/src/parameter.c +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "parameter.h" - -#include - -#include "securec.h" - -static int g_bMockParameter = 0; - -void SetMockParameter(bool para) -{ - g_bMockParameter = para; -} - -bool GetMockParameter(void) -{ - return g_bMockParameter; -} - -uint32_t FindParameter(const char *key) -{ - return 1; -} - -int GetParameterValue(uint32_t handle, char *value, uint32_t len) -{ - errno_t ret = EOK; - if (GetMockParameter()) { - char src[] = "true"; - ret = strncpy_s(value, len, src, strlen(src)); - } else { - char src[] = "false"; - ret = strncpy_s(value, len, src, strlen(src)); - } - return ret == EOK ? 1 : -1; -} \ No newline at end of file diff --git a/tests/mock/parcel/include/parcel.h b/tests/mock/parcel/include/parcel.h deleted file mode 100644 index dd2adf625..000000000 --- a/tests/mock/parcel/include/parcel.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MOCK_OHOS_BACKUP_PARCEL_H -#define MOCK_OHOS_BACKUP_PARCEL_H - -#include - -namespace OHOS::FileManagement::Backup { -void MockWriteUint32(bool state); - -void MockWriteString(bool state, uint8_t count); - -void MockWriteParcelable(bool state); - -void MockReadParcelable(bool state); - -void ResetParcelState(); - -bool GetMockReadParcelableState(); - -class Parcelable; -class Parcel { -public: - Parcel() {} - virtual ~Parcel() = default; - - bool WriteUint32(uint32_t); - - bool WriteString(const std::string &); - - bool WriteParcelable(const Parcelable *); - - bool ReadString(std::string &value); - - bool ReadUint32(uint32_t &value); - - template - T *ReadParcelable() - { - if (GetMockReadParcelableState()) { - return new T(); - } - return nullptr; - } -}; - -class Parcelable { -public: - Parcelable() = default; - virtual ~Parcelable() = default; - virtual bool Marshalling(Parcel &parcel) const = 0; -}; -} // namespace OHOS::FileManagement::Backup -#endif \ No newline at end of file diff --git a/tests/mock/parcel/src/parcel.cpp b/tests/mock/parcel/src/parcel.cpp deleted file mode 100644 index 7b3ed19ed..000000000 --- a/tests/mock/parcel/src/parcel.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "parcel.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -namespace { -bool g_mockWriteUint32 = true; -bool g_mockWriteString = true; -bool g_mockWriteParcelable = true; -bool g_mockReadParcelable = true; -uint8_t g_mockWriteStringCount = 0; -uint8_t g_mockWriteStringMax = 0; -} // namespace - -void MockWriteUint32(bool state) -{ - g_mockWriteUint32 = state; -} - -void MockWriteString(bool state, uint8_t count) -{ - g_mockWriteString = state; - g_mockWriteStringMax = count; -} - -void MockWriteParcelable(bool state) -{ - g_mockWriteParcelable = state; -} - -void MockReadParcelable(bool state) -{ - g_mockReadParcelable = state; -} - -void ResetParcelState() -{ - g_mockWriteUint32 = true; - g_mockWriteString = true; - g_mockWriteParcelable = true; - g_mockReadParcelable = true; - g_mockWriteStringCount = 0; - g_mockWriteStringMax = 0; -} - -bool GetMockReadParcelableState() -{ - return g_mockReadParcelable; -} - -bool Parcel::WriteUint32(uint32_t) -{ - return g_mockWriteUint32; -} - -bool Parcel::WriteString(const string &) -{ - if (g_mockWriteStringCount < g_mockWriteStringMax) { - g_mockWriteStringCount++; - return !g_mockWriteString; - } - return g_mockWriteString; -} - -bool Parcel::WriteParcelable(const Parcelable *) -{ - return g_mockWriteParcelable; -} - -bool Parcel::ReadString(string &value) -{ - if (g_mockWriteStringCount < g_mockWriteStringMax) { - g_mockWriteStringCount++; - return !g_mockWriteString; - } - return g_mockWriteString; -} - -bool Parcel::ReadUint32(uint32_t &value) -{ - return g_mockWriteUint32; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/system_ability_manager/service_registry_mock.cpp b/tests/mock/system_ability_manager/service_registry_mock.cpp deleted file mode 100644 index 32a34e00f..000000000 --- a/tests/mock/system_ability_manager/service_registry_mock.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "iservice_registry.h" - -#include -#include -#include - -#include "system_ability_definition.h" -#include "system_ability_manager_proxy.h" -#include "utils_mock_global_variable.h" - -namespace OHOS { -using namespace FileManagement::Backup; - -SystemAbilityManagerClient &SystemAbilityManagerClient::GetInstance() -{ - static auto instance = new SystemAbilityManagerClient(); - return *instance; -} - -sptr SystemAbilityManagerClient::GetSystemAbilityManager() -{ - GTEST_LOG_(INFO) << "GetSystemAbilityManager is ok"; - std::lock_guard lock(systemAbilityManagerLock_); - if (systemAbilityManager_ != nullptr) { - return systemAbilityManager_; - } - - systemAbilityManager_ = new SystemAbilityManagerProxy(nullptr); - return systemAbilityManager_; -} - -int32_t SystemAbilityManagerProxy::LoadSystemAbility(int32_t systemAbilityId, - const sptr &callback) -{ - GTEST_LOG_(INFO) << "LoadSystemAbility is ok"; - if (!GetMockLoadSystemAbility()) { - return -1; - } - return ERR_OK; -} -} // namespace OHOS \ No newline at end of file diff --git a/tests/mock/timer/timer_mock.cpp b/tests/mock/timer/timer_mock.cpp deleted file mode 100644 index 54a5bcb7c..000000000 --- a/tests/mock/timer/timer_mock.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "timer.h" - -#include -#include - -namespace OHOS { -namespace Utils { - -Timer::Timer(const std::string &name, int timeoutMs) -{ - GTEST_LOG_(INFO) << "Timer " << name << " ,timeoutMs " << timeoutMs; - name_ = name; -} - -uint32_t Timer::Setup() -{ - GTEST_LOG_(INFO) << "Timer Setup"; - return 1; -} - -uint32_t Timer::Register(const TimerCallback &callback, uint32_t interval, bool once) -{ - GTEST_LOG_(INFO) << "Timer Register " << interval; - callback(); - return 1; -} - -void Timer::Shutdown(bool useJoin) -{ - GTEST_LOG_(INFO) << "Timer Shutdown " << useJoin; -} - -void Timer::Unregister(uint32_t timerId) -{ - GTEST_LOG_(INFO) << "Timer Unregister " << timerId; -} -} // namespace Utils -} // namespace OHOS diff --git a/tests/mock/utils_mock/include/iremote_object_mock.h b/tests/mock/utils_mock/include/iremote_object_mock.h deleted file mode 100644 index 4ae9fd155..000000000 --- a/tests/mock/utils_mock/include/iremote_object_mock.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_IREMOTE_OBJECT_MOCK_H -#define OHOS_FILEMGMT_BACKUP_IREMOTE_OBJECT_MOCK_H - -#include - -#include "iremote_object.h" - -namespace OHOS::FileManagement::Backup { -class MockIRemoteObject : public IRemoteObject { -public: - MockIRemoteObject() : IRemoteObject(u"mock_i_remote_object") - { - GTEST_LOG_(INFO) << "MockIRemoteObject is ok"; - } - - ~MockIRemoteObject() {} - - int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override - { - return 0; - } - - int32_t GetObjectRefCount() override - { - return 0; - } - - bool CheckObjectLegality() const override - { - return true; - } - - bool IsProxyObject() const override - { - return true; - } - - bool AddDeathRecipient(const sptr &recipient) override - { - GTEST_LOG_(INFO) << "AddDeathRecipient is ok"; - return true; - } - - bool RemoveDeathRecipient(const sptr &recipient) override - { - return true; - } - - sptr AsInterface() override - { - return nullptr; - } - - bool Marshalling(Parcel &parcel) const override - { - return true; - } - - std::u16string GetObjectDescriptor() const - { - std::u16string descriptor = std::u16string(); - return descriptor; - } - - int Dump(int fd, const std::vector &args) override - { - return 0; - } -}; -} // namespace OHOS::FileManagement::Backup -#endif \ No newline at end of file diff --git a/tests/mock/utils_mock/include/utils_mock_global_variable.h b/tests/mock/utils_mock/include/utils_mock_global_variable.h deleted file mode 100644 index 5bfa7a42a..000000000 --- a/tests/mock/utils_mock/include/utils_mock_global_variable.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MOCK_OHOS_BACKUP_UTILS_MOCK_GLOBAL_VARIABLE_H -#define MOCK_OHOS_BACKUP_UTILS_MOCK_GLOBAL_VARIABLE_H - -namespace OHOS::FileManagement::Backup { -void SetMockGetInstance(bool state); -void SetMockInitBackupOrRestoreSession(bool state); -bool GetMockGetInstance(); -bool GetMockInitBackupOrRestoreSession(); -void SetMockLoadSystemAbility(bool state); -bool GetMockLoadSystemAbility(); -} // namespace OHOS::FileManagement::Backup -#endif \ No newline at end of file diff --git a/tests/mock/utils_mock/src/utils_mock_global_variable.cpp b/tests/mock/utils_mock/src/utils_mock_global_variable.cpp deleted file mode 100644 index 5696ca7a6..000000000 --- a/tests/mock/utils_mock/src/utils_mock_global_variable.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "utils_mock_global_variable.h" - -namespace OHOS::FileManagement::Backup { -namespace { -static bool g_bMockGetInstance = true; -static bool g_bMockInitBackupOrRestoreSession = true; -static bool g_bMockLoadSystemAbility = true; -} // namespace - -void SetMockGetInstance(bool state) -{ - g_bMockGetInstance = state; -} - -void SetMockInitBackupOrRestoreSession(bool state) -{ - g_bMockInitBackupOrRestoreSession = state; -} - -bool GetMockGetInstance() -{ - return g_bMockGetInstance; -} - -bool GetMockInitBackupOrRestoreSession() -{ - return g_bMockInitBackupOrRestoreSession; -} - -void SetMockLoadSystemAbility(bool state) -{ - g_bMockLoadSystemAbility = state; -} - -bool GetMockLoadSystemAbility() -{ - return g_bMockLoadSystemAbility; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/moduletests/BUILD.gn b/tests/moduletests/BUILD.gn deleted file mode 100644 index 5de2e6da9..000000000 --- a/tests/moduletests/BUILD.gn +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -group("moduletests") { - testonly = true - - deps = [ - "backup_kit_inner:session_test", - "backup_tool:tools_test", - ] -} diff --git a/tests/moduletests/backup_kit_inner/BUILD.gn b/tests/moduletests/backup_kit_inner/BUILD.gn deleted file mode 100644 index 32646475f..000000000 --- a/tests/moduletests/backup_kit_inner/BUILD.gn +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_unittest("b_session_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_backup.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_restore.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", - "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", - "b_session_backup_test.cpp", - "b_session_restore_test.cpp", - ] - sources += backup_mock_proxy_src - - include_dirs = [ - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - "${path_backup}/frameworks/native/backup_kit_inner/include", - ] - include_dirs += backup_mock_utils_include - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - ] - - external_deps = [ - "ipc:ipc_core", - "samgr:samgr_proxy", - ] - - use_exceptions = true -} - -group("session_test") { - testonly = true - - deps = [ ":b_session_test" ] -} diff --git a/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp b/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp deleted file mode 100644 index 0f1f5a685..000000000 --- a/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "b_error/b_error.h" -#include "b_file_info.h" -#include "backup_kit_inner.h" -#include "unique_fd.h" -#include "utils_mock_global_variable.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -static void OnFileReady(const BFileInfo &fileInfo, UniqueFd fd) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest OnFileReady OK"; -} - -static void OnBundleStarted(ErrCode err, const BundleName name) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest OnBundleStarted OK"; -} - -static void OnBundleFinished(ErrCode err, const BundleName name) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest OnBundleFinished OK"; -} - -static void OnAllBundlesFinished(ErrCode err) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest OnAllBundlesFinished OK"; -} - -static void OnBackupServiceDied() -{ - GTEST_LOG_(INFO) << "BSessionBackupTest OnBackupServiceDied OK"; -} - -class BSessionBackupTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override; - void TearDown() override; - - void Init(); - - unique_ptr backupPtr_; - BSessionBackup::Callbacks callbacks_; -}; - -void BSessionBackupTest::SetUp() -{ - SetMockInitBackupOrRestoreSession(true); - SetMockGetInstance(true); - SetMockLoadSystemAbility(true); - backupPtr_ = make_unique(); -} - -void BSessionBackupTest::TearDown() -{ - backupPtr_ = nullptr; -} - -void BSessionBackupTest::Init() -{ - callbacks_.onFileReady = OnFileReady; - callbacks_.onBundleStarted = OnBundleStarted; - callbacks_.onBundleFinished = OnBundleFinished; - callbacks_.onAllBundlesFinished = OnAllBundlesFinished; - callbacks_.onBackupServiceDied = OnBackupServiceDied; -} - -/** - * @tc.number: SUB_backup_b_session_backup_0100 - * @tc.name: SUB_backup_b_session_backup_0100 - * @tc.desc: 测试Start接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest-begin SUB_backup_b_session_backup_0100"; - try { - GTEST_LOG_(INFO) << "GetInstance is true"; - auto ret = backupPtr_->Start(); - EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - ret = backupPtr_->Start(); - EXPECT_NE(ret, ErrCode(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by Start."; - } - GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0100"; -} - -/** - * @tc.number: SUB_backup_b_session_backup_0200 - * @tc.name: SUB_backup_b_session_backup_0200 - * @tc.desc: 测试Callbacks接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest-begin SUB_backup_b_session_backup_0200"; - try { - Init(); - BFileInfo bFileInfo("", "", 0); - callbacks_.onFileReady(bFileInfo, UniqueFd(-1)); - callbacks_.onBundleStarted(ErrCode(BError::Codes::OK), ""); - callbacks_.onBundleFinished(ErrCode(BError::Codes::OK), ""); - callbacks_.onAllBundlesFinished(ErrCode(BError::Codes::OK)); - callbacks_.onBackupServiceDied(); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by Callbacks."; - } - GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0200"; -} - -/** - * @tc.number: SUB_backup_b_session_backup_0300 - * @tc.name: SUB_backup_b_session_backup_0300 - * @tc.desc: 测试Init接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0300, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest-begin SUB_backup_b_session_backup_0300"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - vector bundlesToBackup; - auto backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, BSessionBackup::Callbacks {}); - EXPECT_EQ(backupPtr, nullptr); - GTEST_LOG_(INFO) << "GetInstance is true"; - GTEST_LOG_(INFO) << "InitBackupSession is false"; - SetMockGetInstance(true); - SetMockInitBackupOrRestoreSession(false); - backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, BSessionBackup::Callbacks {}); - EXPECT_EQ(backupPtr, nullptr); - GTEST_LOG_(INFO) << "InitBackupSession is true"; - SetMockInitBackupOrRestoreSession(true); - Init(); - backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, callbacks_); - EXPECT_NE(backupPtr, nullptr); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by Init."; - } - GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0300"; -} - -/** - * @tc.number: SUB_backup_b_session_backup_0400 - * @tc.name: SUB_backup_b_session_backup_0400 - * @tc.desc: 测试RegisterBackupServiceDied接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0400, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest-begin SUB_backup_b_session_backup_0400"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - backupPtr_->RegisterBackupServiceDied(nullptr); - GTEST_LOG_(INFO) << "GetInstance is true"; - SetMockGetInstance(true); - backupPtr_->RegisterBackupServiceDied(nullptr); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by RegisterBackupServiceDied."; - } - GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0400"; -} - -/** - * @tc.number: SUB_backup_b_session_backup_0500 - * @tc.name: SUB_backup_b_session_backup_0500 - * @tc.desc: 测试析构流程接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0500, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionBackupTest-begin SUB_backup_b_session_backup_0500"; - try { - SetMockGetInstance(true); - SetMockLoadSystemAbility(true); - vector bundlesToBackup; - Init(); - auto backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, callbacks_); - EXPECT_NE(backupPtr, nullptr); - - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - backupPtr = nullptr; - - SetMockGetInstance(true); - SetMockLoadSystemAbility(true); - backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, callbacks_); - EXPECT_NE(backupPtr, nullptr); - - GTEST_LOG_(INFO) << "LoadSystemAbility is false"; - SetMockLoadSystemAbility(false); - backupPtr = nullptr; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by ~BSessionBackup."; - } - GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0500"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/moduletests/backup_kit_inner/b_session_restore_test.cpp b/tests/moduletests/backup_kit_inner/b_session_restore_test.cpp deleted file mode 100644 index bdd3325ff..000000000 --- a/tests/moduletests/backup_kit_inner/b_session_restore_test.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "b_error/b_error.h" -#include "b_file_info.h" -#include "backup_kit_inner.h" -#include "unique_fd.h" -#include "utils_mock_global_variable.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -static void OnFileReady(const BFileInfo &fileInfo, UniqueFd fd) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest OnFileReady OK"; -} - -static void OnBundleStarted(ErrCode err, const BundleName name) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest OnBundleStarted OK"; -} - -static void OnBundleFinished(ErrCode err, const BundleName name) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest OnBundleFinished OK"; -} - -static void OnAllBundlesFinished(ErrCode err) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest OnAllBundlesFinished OK"; -} - -static void OnBackupServiceDied() -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest OnBackupServiceDied OK"; -} - -class BSessionRestoreTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override; - void TearDown() override; - - void Init(); - - unique_ptr restorePtr_; - BSessionRestore::Callbacks callbacks_; -}; - -void BSessionRestoreTest::SetUp() -{ - SetMockInitBackupOrRestoreSession(true); - SetMockGetInstance(true); - SetMockLoadSystemAbility(true); - restorePtr_ = unique_ptr(); -} - -void BSessionRestoreTest::TearDown() -{ - restorePtr_ = nullptr; -} - -void BSessionRestoreTest::Init() -{ - callbacks_.onFileReady = OnFileReady; - callbacks_.onBundleStarted = OnBundleStarted; - callbacks_.onBundleFinished = OnBundleFinished; - callbacks_.onAllBundlesFinished = OnAllBundlesFinished; - callbacks_.onBackupServiceDied = OnBackupServiceDied; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0100 - * @tc.name: SUB_backup_b_session_restore_0100 - * @tc.desc: 测试Start接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0100"; - try { - GTEST_LOG_(INFO) << "GetInstance is true"; - auto ret = restorePtr_->Start(); - EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - ret = restorePtr_->Start(); - EXPECT_NE(ret, ErrCode(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by Start."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0100"; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0200 - * @tc.name: SUB_backup_b_session_restore_0200 - * @tc.desc: 测试Callbacks接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0200"; - try { - Init(); - BFileInfo bFileInfo("", "", 0); - callbacks_.onFileReady(bFileInfo, UniqueFd(-1)); - callbacks_.onBundleStarted(ErrCode(BError::Codes::OK), ""); - callbacks_.onBundleFinished(ErrCode(BError::Codes::OK), ""); - callbacks_.onAllBundlesFinished(ErrCode(BError::Codes::OK)); - callbacks_.onBackupServiceDied(); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by Callbacks."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0200"; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0300 - * @tc.name: SUB_backup_b_session_restore_0300 - * @tc.desc: 测试Init接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0300, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0300"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - vector bundlesToBackup; - auto restorePtr = BSessionRestore::Init(bundlesToBackup, {}); - EXPECT_EQ(restorePtr, nullptr); - GTEST_LOG_(INFO) << "GetInstance is true"; - GTEST_LOG_(INFO) << "InitBackupSession is false"; - SetMockGetInstance(true); - SetMockInitBackupOrRestoreSession(false); - restorePtr = BSessionRestore::Init(bundlesToBackup, {}); - EXPECT_EQ(restorePtr, nullptr); - GTEST_LOG_(INFO) << "InitBackupSession is true"; - SetMockInitBackupOrRestoreSession(true); - Init(); - restorePtr = BSessionRestore::Init(bundlesToBackup, callbacks_); - EXPECT_NE(restorePtr, nullptr); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by Init."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0300"; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0400 - * @tc.name: SUB_backup_b_session_restore_0400 - * @tc.desc: 测试GetLocalCapabilities接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0400, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0400"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - auto fd = restorePtr_->GetLocalCapabilities(); - EXPECT_NE(fd, 0); - GTEST_LOG_(INFO) << "GetInstance is true"; - SetMockGetInstance(true); - fd = restorePtr_->GetLocalCapabilities(); - EXPECT_NE(fd, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by GetLocalCapabilities."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0400"; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0500 - * @tc.name: SUB_backup_b_session_restore_0500 - * @tc.desc: 测试PublishFile接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0500, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0500"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - BFileInfo bFileInfo("", "", 0); - auto ret = restorePtr_->PublishFile(bFileInfo); - EXPECT_NE(ret, ErrCode(BError::Codes::OK)); - GTEST_LOG_(INFO) << "GetInstance is true"; - SetMockGetInstance(true); - ret = restorePtr_->PublishFile(bFileInfo); - EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by PublishFile."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0500"; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0600 - * @tc.name: SUB_backup_b_session_restore_0600 - * @tc.desc: 测试GetExtFileName接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0600, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0600"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - string bundleName = ""; - string fileName = ""; - auto ret = restorePtr_->GetExtFileName(bundleName, fileName); - EXPECT_NE(ret, ErrCode(BError::Codes::OK)); - GTEST_LOG_(INFO) << "GetInstance is true"; - SetMockGetInstance(true); - ret = restorePtr_->GetExtFileName(bundleName, fileName); - EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by GetExtFileName."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0600"; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0700 - * @tc.name: SUB_backup_b_session_restore_0700 - * @tc.desc: 测试RegisterBackupServiceDied接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0700, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0700"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - restorePtr_->RegisterBackupServiceDied(nullptr); - GTEST_LOG_(INFO) << "GetInstance is true"; - SetMockGetInstance(true); - restorePtr_->RegisterBackupServiceDied(nullptr); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by RegisterBackupServiceDied."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0700"; -} - -/** - * @tc.number: SUB_backup_b_session_restore_0800 - * @tc.name: SUB_backup_b_session_restore_0800 - * @tc.desc: 测试析构流程接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0800, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0800"; - try { - vector bundlesToBackup; - SetMockGetInstance(true); - SetMockLoadSystemAbility(true); - Init(); - auto restorePtr = BSessionRestore::Init(bundlesToBackup, callbacks_); - EXPECT_NE(restorePtr, nullptr); - - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - restorePtr = nullptr; - - SetMockGetInstance(true); - SetMockLoadSystemAbility(true); - restorePtr = BSessionRestore::Init(bundlesToBackup, callbacks_); - EXPECT_NE(restorePtr, nullptr); - - GTEST_LOG_(INFO) << "LoadSystemAbility is false"; - SetMockLoadSystemAbility(false); - restorePtr = nullptr; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by ~BSessionRestore."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0800"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/moduletests/backup_tool/BUILD.gn b/tests/moduletests/backup_tool/BUILD.gn deleted file mode 100644 index 1b2d4fdb3..000000000 --- a/tests/moduletests/backup_tool/BUILD.gn +++ /dev/null @@ -1,37 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_unittest("tools_op_test") { - module_out_path = path_module_out_tests - - sources = [ - "tool_backup_restore_test.cpp", - "tool_help_test.cpp", - ] - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils/:backup_utils", - ] - - use_exceptions = true -} - -group("tools_test") { - testonly = true - - deps = [ ":tools_op_test" ] -} diff --git a/tests/moduletests/backup_tool/tool_backup_restore_test.cpp b/tests/moduletests/backup_tool/tool_backup_restore_test.cpp deleted file mode 100644 index e0ab9397a..000000000 --- a/tests/moduletests/backup_tool/tool_backup_restore_test.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "b_process/b_process.h" -#include "test_manager.h" -#include "gtest/gtest.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -class ToolsTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/moduletests/backup_tool/tool_help_test.cpp b/tests/moduletests/backup_tool/tool_help_test.cpp deleted file mode 100644 index 26ad00ab1..000000000 --- a/tests/moduletests/backup_tool/tool_help_test.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_process/b_process.h" -#include "test_manager.h" -#include "gtest/gtest.h" - -namespace OHOS::FileManagement::Backup { -class ToolsTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_tool_help_0100 - * @tc.name: tool_help_0100 - * @tc.desc: 测试help命令常规用法 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsTest, tool_help_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ToolsTest-begin tool_help_0100"; - try { - auto [bFatalError, ret] = BProcess::ExecuteCmd({ - "/system/bin/backup_tool", - "help", - }); - EXPECT_EQ(ret, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "ToolsTest-end tool_help_0100"; -} - -/** - * @tc.number: SUB_backup_tool_help_0200 - * @tc.name: tool_help_0200 - * @tc.desc: 测试help命令错误使用 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsTest, tool_help_0200, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ToolsTest-begin tool_help_0200"; - try { - auto [bFatalError, ret] = BProcess::ExecuteCmd({ - "/system/bin/backup_tool", - "xxxx", - }); - EXPECT_NE(ret, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "ToolsTest-end tool_help_0200"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/BUILD.gn b/tests/unittests/BUILD.gn deleted file mode 100644 index 686cdadaf..000000000 --- a/tests/unittests/BUILD.gn +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -group("unittests") { - testonly = true - - deps = [ - "backup_api:backup_api_test", - "backup_sa:backup_sa_test", - "backup_tools:backup_test", - "backup_utils:backup_test", - ] -} diff --git a/tests/unittests/backup_api/BUILD.gn b/tests/unittests/backup_api/BUILD.gn deleted file mode 100644 index bd497d39b..000000000 --- a/tests/unittests/backup_api/BUILD.gn +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -group("backup_api_test") { - testonly = true - - deps = [ "backup_impl:backup_impl_test" ] -} diff --git a/tests/unittests/backup_api/backup_impl/BUILD.gn b/tests/unittests/backup_api/backup_impl/BUILD.gn deleted file mode 100644 index 2692698a1..000000000 --- a/tests/unittests/backup_api/backup_impl/BUILD.gn +++ /dev/null @@ -1,80 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_unittest("b_file_info_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup}/frameworks/native/backup_kit_inner/src/b_file_info.cpp", - "b_file_info_test.cpp", - ] - sources += backup_mock_parcel_src - - include_dirs = - [ "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl" ] - include_dirs += backup_mock_parcel_include_dirs - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - ] - - use_exceptions = true -} - -ohos_unittest("backup_sa_impl_test") { - module_out_path = "filemanagement/backup" - - sources = [ - "${path_backup_mock}/system_ability_manager/service_registry_mock.cpp", - "${path_backup_mock}/utils_mock/src/utils_mock_global_variable.cpp", - "service_proxy_test.cpp", - "service_reverse_stub_test.cpp", - "service_reverse_test.cpp", - "svc_death_recipient_test.cpp", - ] - - include_dirs = [ - "${path_backup}/services/backup_sa/include", - "${path_backup}/frameworks/native/backup_kit_inner/include", - "${path_backup}/tests/unittests/backup_api/backup_impl/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - ] - include_dirs += backup_mock_utils_include - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - "${path_googletest}:gmock_main", - ] - - external_deps = [ - "app_file_service:backup_kit_inner", - "ipc:ipc_core", - "samgr:samgr_proxy", - ] - - use_exceptions = true -} - -group("backup_impl_test") { - testonly = true - - deps = [ - ":b_file_info_test", - ":backup_sa_impl_test", - ] -} diff --git a/tests/unittests/backup_api/backup_impl/b_file_info_test.cpp b/tests/unittests/backup_api/backup_impl/b_file_info_test.cpp deleted file mode 100644 index e029d7050..000000000 --- a/tests/unittests/backup_api/backup_impl/b_file_info_test.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "b_file_info.h" -#include "parcel.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -const string FILE_NAME = "1.tar"; -} // namespace - -class BFileInfoTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override {}; - void TearDown() override {}; -}; - -/** - * @tc.number: SUB_BFile_Info_Marshalling_0100 - * @tc.name: SUB_BFile_Info_Marshalling_0100 - * @tc.desc: Test function of Marshalling interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BFileInfoTest, SUB_BFile_Info_Marshalling_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BFileInfoTest-begin SUB_BFile_Info_Marshalling_0100"; - BFileInfo bFileInfo(BUNDLE_NAME, FILE_NAME, -1); - Parcel parcel; - // marshalling - EXPECT_EQ(bFileInfo.Marshalling(parcel), true); - // unmarshalling - auto infoPtr = bFileInfo.Unmarshalling(parcel); - EXPECT_NE(infoPtr, nullptr); - GTEST_LOG_(INFO) << "BFileInfoTest-end SUB_BFile_Info_Marshalling_0100"; -} - -/** - * @tc.number: SUB_BFile_Info_ReadFromParcel_0100 - * @tc.name: SUB_BFile_Info_ReadFromParcel_0100 - * @tc.desc: Test function of ReadFromParcel interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BFileInfoTest, SUB_BFile_Info_ReadFromParcel_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BFileInfoTest-begin SUB_BFile_Info_ReadFromParcel_0100"; - BFileInfo bFileInfo(BUNDLE_NAME, FILE_NAME, -1); - Parcel parcel; - // marshalling - EXPECT_EQ(bFileInfo.Marshalling(parcel), true); - - // ReadFromParcel - BFileInfo bFileInfoTemp {"", "", -1}; - bFileInfoTemp.ReadFromParcel(parcel); - GTEST_LOG_(INFO) << "BFileInfoTest-end SUB_BFile_Info_ReadFromParcel_0100"; -} - -/** - * @tc.number: SUB_BFile_Info_Unmarshalling_0100 - * @tc.name: SUB_BFile_Info_Unmarshalling_0100 - * @tc.desc: Test function of Unmarshalling interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BFileInfoTest, SUB_BFile_Info_Unmarshalling_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BFileInfoTest-begin SUB_BFile_Info_Unmarshalling_0100"; - BFileInfo bFileInfo(BUNDLE_NAME, FILE_NAME, -1); - Parcel parcel; - // marshalling - EXPECT_EQ(bFileInfo.Marshalling(parcel), true); - // unmarshalling - BFileInfo bFileInfoTemp {"", "", -1}; - auto infoPtr = bFileInfoTemp.Unmarshalling(parcel); - EXPECT_NE(infoPtr, nullptr); - GTEST_LOG_(INFO) << "BFileInfoTest-end SUB_BFile_Info_Unmarshalling_0100"; -} - -/** - * @tc.number: SUB_BFile_Info_0200 - * @tc.name: SUB_BFile_Info_0200 - * @tc.desc: 分支测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BFileInfoTest, SUB_BFile_Info_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BFileInfoTest-begin SUB_BFile_Info_0200"; - BFileInfo bFileInfo(BUNDLE_NAME, FILE_NAME, -1); - Parcel parcel; - ResetParcelState(); - MockWriteUint32(false); - EXPECT_EQ(bFileInfo.Marshalling(parcel), false); - MockWriteUint32(true); - MockWriteString(false, 1); - EXPECT_EQ(bFileInfo.Marshalling(parcel), false); - EXPECT_EQ(bFileInfo.Marshalling(parcel), false); - - ResetParcelState(); - MockWriteUint32(false); - EXPECT_EQ(bFileInfo.ReadFromParcel(parcel), false); - MockWriteUint32(true); - MockWriteString(false, 1); - EXPECT_EQ(bFileInfo.ReadFromParcel(parcel), false); - EXPECT_EQ(bFileInfo.ReadFromParcel(parcel), false); - - auto infoPtr = bFileInfo.Unmarshalling(parcel); - EXPECT_EQ(infoPtr, nullptr); - - GTEST_LOG_(INFO) << "BFileInfoTest-end SUB_BFile_Info_0200"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h deleted file mode 100644 index e3a3bb1c8..000000000 --- a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MOCK_EXTENSION_MOCK_H -#define MOCK_EXTENSION_MOCK_H - -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "i_extension.h" -#include "iremote_stub.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -class BackupExtExtensionMock : public IRemoteStub { -public: - int code_ = 0; - BackupExtExtensionMock() : code_(0) {} - virtual ~BackupExtExtensionMock() {} - - MOCK_METHOD4(SendRequest, int(uint32_t, MessageParcel &, MessageParcel &, MessageOption &)); - - int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - reply.WriteInt32(BError(BError::Codes::OK)); - return BError(BError::Codes::OK); - } - - int32_t InvokeGetFileHandleRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - std::string fileName = "1.tar"; - TestManager tm("GetFileHand_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(fileName); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - reply.WriteFileDescriptor(fd); - return BError(BError::Codes::OK); - } - - UniqueFd GetFileHandle(const std::string &fileName) override - { - GTEST_LOG_(INFO) << "GetFileHandle" << fileName; - if (fileName == "testName") { - return UniqueFd(-1); - } - - if (fileName.empty()) { - return UniqueFd(-1); - } - TestManager tm("GetFileHand_GetFd_0200"); - std::string filePath = tm.GetRootDirCurTest().append(fileName); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - return fd; - }; - - ErrCode HandleClear() override - { - return BError(BError::Codes::OK); - }; - - ErrCode HandleBackup() override - { - GTEST_LOG_(INFO) << "HandleBackup"; - if (nHandleBackupNum_ == 1) { - GTEST_LOG_(INFO) << "HandleBackup is false"; - return 1; - } - nHandleBackupNum_++; - return BError(BError::Codes::OK); - }; - - ErrCode PublishFile(const std::string &fileName) override - { - GTEST_LOG_(INFO) << "PublishFile " << fileName; - if (fileName == "test") { - return 1; - } - return BError(BError::Codes::OK); - }; - -private: - int32_t nHandleBackupNum_ = 0; -}; -} // namespace OHOS::FileManagement::Backup -#endif // MOCK_EXTENSION_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h deleted file mode 100644 index 5fe4f5057..000000000 --- a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MOCK_I_SERVICE_MOCK_H -#define MOCK_I_SERVICE_MOCK_H - -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "i_service.h" -#include "iremote_stub.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -class IServiceMock : public IRemoteStub { -public: - int code_ = 0; - IServiceMock() : code_(0) {} - virtual ~IServiceMock() {} - - MOCK_METHOD4(SendRequest, int(uint32_t, MessageParcel &, MessageParcel &, MessageOption &)); - - int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - code_ = code; - reply.WriteInt32(BError(BError::Codes::OK)); - return BError(BError::Codes::OK); - } - - int32_t InvokeGetLocalSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - code_ = code; - std::string fileName = "1.tar"; - TestManager tm("GetLocalCap_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(fileName); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - reply.WriteFileDescriptor(fd); - return BError(BError::Codes::OK); - } - - ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) override - { - return BError(BError::Codes::OK); - } - - ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) override - { - return BError(BError::Codes::OK); - } - - ErrCode Start() override - { - return BError(BError::Codes::OK); - } - - UniqueFd GetLocalCapabilities() override - { - return UniqueFd(-1); - } - - ErrCode PublishFile(const BFileInfo &fileInfo) override - { - return BError(BError::Codes::OK); - } - - ErrCode AppFileReady(const std::string &fileName, UniqueFd fd) override - { - return BError(BError::Codes::OK); - } - - ErrCode AppDone(ErrCode errCode) override - { - return BError(BError::Codes::OK); - } - - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) override - { - return BError(BError::Codes::OK); - } -}; -} // namespace OHOS::FileManagement::Backup -#endif // MOCK_I_SERVICE_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h b/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h deleted file mode 100644 index e4f6e2a2a..000000000 --- a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MOCK_SERVICE_REVERSE_MOCK_H -#define MOCK_SERVICE_REVERSE_MOCK_H - -#include - -#include "b_error/b_error.h" -#include "i_service_reverse.h" -#include "iremote_stub.h" - -namespace OHOS::FileManagement::Backup { -class ServiceReverseMock : public IRemoteStub { -public: - int code_ = 0; - ServiceReverseMock() : code_(0) {} - virtual ~ServiceReverseMock() {} - - MOCK_METHOD4(SendRequest, int(uint32_t, MessageParcel &, MessageParcel &, MessageOption &)); - - int32_t InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - code_ = code; - return BError(BError::Codes::OK); - } - void BackupOnFileReady(std::string bundleName, std::string fileName, int fd) override {} - void BackupOnBundleStarted(int32_t errCode, std::string bundleName) override {} - void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override {} - void BackupOnAllBundlesFinished(int32_t errCode) override {} - - void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {} - void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {} - void RestoreOnAllBundlesFinished(int32_t errCode) override {} - void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) override {} -}; -} // namespace OHOS::FileManagement::Backup -#endif // MOCK_SERVICE_REVERSE_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp deleted file mode 100644 index 417a1ecbb..000000000 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include "b_file_info.h" -#include "i_service_mock.h" -#include "iremote_object_mock.h" -#include "iservice_registry.h" -#include "service_proxy.h" -#include "service_reverse_mock.h" -#include "unique_fd.h" -#include "utils_mock_global_variable.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string FILE_NAME = "1.tar"; -constexpr int32_t SERVICE_ID = 5203; -} // namespace - -class ServiceProxyTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override; - void TearDown() override; - - shared_ptr proxy_ = nullptr; - sptr mock_ = nullptr; - sptr remote_ = nullptr; -}; - -void ServiceProxyTest::SetUp() -{ - mock_ = sptr(new IServiceMock()); - proxy_ = make_shared(mock_); - remote_ = sptr(new ServiceReverseMock()); -} - -void ServiceProxyTest::TearDown() -{ - proxy_ = nullptr; - mock_ = nullptr; - remote_ = nullptr; -} - -/** - * @tc.number: SUB_Service_proxy_InitRestoreSession_0100 - * @tc.name: SUB_Service_proxy_InitRestoreSession_0100 - * @tc.desc: 测试 InitRestoreSession 注册restore Session接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_InitRestoreSession_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_InitRestoreSession_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - std::vector bundleNames; - int32_t result = proxy_->InitRestoreSession(remote_, bundleNames); - EXPECT_EQ(result, BError(BError::Codes::OK)); - - result = proxy_->InitRestoreSession(remote_, bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - result = proxy_->InitRestoreSession(nullptr, bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_InitRestoreSession_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_InitBackupSession_0100 - * @tc.name: SUB_Service_proxy_InitBackupSession_0100 - * @tc.desc: 测试 InitBackupSession 注册backup Session接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_InitBackupSession_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_InitBackupSession_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - std::vector bundleNames; - - TestManager tm("BackupSession_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - int32_t result = proxy_->InitBackupSession(remote_, move(fd), bundleNames); - EXPECT_EQ(result, BError(BError::Codes::OK)); - - result = proxy_->InitRestoreSession(remote_, bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - result = proxy_->InitBackupSession(nullptr, move(fd), bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - result = proxy_->InitBackupSession(remote_, UniqueFd(-1), bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_InitBackupSession_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_Start_0100 - * @tc.name: SUB_Service_proxy_Start_0100 - * @tc.desc: 测试 Start 启动备份恢复流程接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_Start_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_Start_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - int32_t result = proxy_->Start(); - EXPECT_EQ(result, BError(BError::Codes::OK)); - - result = proxy_->Start(); - EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_Start_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_GetLocalCapabilities_0100 - * @tc.name: SUB_Service_proxy_GetLocalCapabilities_0100 - * @tc.desc: 测试 GetLocalCapabilities 获取能力文件接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_GetLocalCapabilities_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_GetLocalCapabilities_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeGetLocalSendRequest)) - .WillOnce(Return(EPERM)); - UniqueFd fd = proxy_->GetLocalCapabilities(); - EXPECT_GT(fd, BError(BError::Codes::OK)); - - UniqueFd fdErr = proxy_->GetLocalCapabilities(); - EXPECT_LT(fdErr, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_GetLocalCapabilities_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_PublishFile_0100 - * @tc.name: SUB_Service_proxy_PublishFile_0100 - * @tc.desc: 测试 PublishFile 推送接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_PublishFile_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_PublishFile_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - string bundleName = "com.example.app2backup"; - string fileName = "1.tar"; - BFileInfo fileInfo(bundleName, fileName, -1); - int32_t result = proxy_->PublishFile(fileInfo); - EXPECT_EQ(result, BError(BError::Codes::OK)); - - result = proxy_->PublishFile(fileInfo); - EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_PublishFile_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_AppFileReady_0100 - * @tc.name: SUB_Service_proxy_AppFileReady_0100 - * @tc.desc: 测试 AppFileReady 文件就绪调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_AppFileReady_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - - string bundleName = "com.example.app2backup"; - TestManager tm("AppFileReady_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - - int32_t result = proxy_->AppFileReady(bundleName, move(fd)); - EXPECT_EQ(result, BError(BError::Codes::OK)); - - TestManager tmErr("AppFileReady_GetFd_0200"); - UniqueFd fdErr(open(tmErr.GetRootDirCurTest().append(FILE_NAME).data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - result = proxy_->AppFileReady(bundleName, move(fdErr)); - EXPECT_NE(result, BError(BError::Codes::OK)); - result = proxy_->AppFileReady(bundleName, UniqueFd(-1)); - EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppFileReady_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_AppDone_0100 - * @tc.name: SUB_Service_proxy_AppDone_0100 - * @tc.desc: 测试 AppDone ext备份恢复流程结束调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppDone_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_AppDone_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - int32_t result = proxy_->AppDone(BError(BError::Codes::OK)); - EXPECT_EQ(result, BError(BError::Codes::OK)); - - result = proxy_->AppDone(BError(BError::Codes::OK)); - EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppDone_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_GetExtFileName_0100 - * @tc.name: SUB_Service_proxy_GetExtFileName_0100 - * @tc.desc: 测试 GetExtFileName 获取真实文件调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_GetExtFileName_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_GetExtFileName_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - string bundleName = "com.example.app2backup"; - string fileName = "1.tar"; - int32_t result = proxy_->GetExtFileName(bundleName, fileName); - EXPECT_EQ(result, BError(BError::Codes::OK)); - - result = proxy_->GetExtFileName(bundleName, fileName); - EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_GetExtFileName_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_OnLoadSystemAbilitySuccess_0100 - * @tc.name: SUB_Service_proxy_OnLoadSystemAbilitySuccess_0100 - * @tc.desc: 测试 OnLoadSystemAbilitySuccess 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_OnLoadSystemAbilitySuccess_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_OnLoadSystemAbilitySuccess_0100"; - sptr loadCallback = new ServiceProxy::ServiceProxyLoadCallback(); - EXPECT_NE(loadCallback, nullptr); - loadCallback->OnLoadSystemAbilitySuccess(SERVICE_ID, nullptr); - loadCallback = nullptr; - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_OnLoadSystemAbilitySuccess_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_OnLoadSystemAbilityFail_0100 - * @tc.name: SUB_Service_proxy_OnLoadSystemAbilityFail_0100 - * @tc.desc: 测试 OnLoadSystemAbilityFail 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_OnLoadSystemAbilityFail_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_OnLoadSystemAbilityFail_0100"; - sptr loadCallback = new ServiceProxy::ServiceProxyLoadCallback(); - EXPECT_NE(loadCallback, nullptr); - loadCallback->OnLoadSystemAbilityFail(SERVICE_ID); - loadCallback = nullptr; - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_OnLoadSystemAbilityFail_0100"; -} - -/** - * @tc.number: SUB_Service_proxy_GetInstance_0100 - * @tc.name: SUB_Service_proxy_GetInstance_0100 - * @tc.desc: 测试 GetInstance 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_GetInstance_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_GetInstance_0100"; - GTEST_LOG_(INFO) << "MockLoadSystemAbility is false"; - SetMockLoadSystemAbility(false); - auto proxy = ServiceProxy::GetInstance(); - EXPECT_EQ(proxy, nullptr); - GTEST_LOG_(INFO) << "MockLoadSystemAbility is true"; - SetMockLoadSystemAbility(true); - proxy = ServiceProxy::GetInstance(); - EXPECT_EQ(proxy, nullptr); - sptr loadCallback = new ServiceProxy::ServiceProxyLoadCallback(); - sptr object = new MockIRemoteObject(); - loadCallback->OnLoadSystemAbilitySuccess(SERVICE_ID, object); - GTEST_LOG_(INFO) << "GetInstance is ok"; - proxy = ServiceProxy::GetInstance(); - EXPECT_NE(proxy, nullptr); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_GetInstance_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp b/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp deleted file mode 100644 index 783a5006c..000000000 --- a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "i_service_reverse.h" -#include "service_reverse_stub.h" -#include "test_manager.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -const string FILE_NAME = "1.tar"; -} // namespace - -class MockServiceReverse final : public ServiceReverseStub { -public: - MOCK_METHOD3(BackupOnFileReady, void(string bundleName, string fileName, int fd)); - MOCK_METHOD2(BackupOnBundleStarted, void(int32_t errCode, string bundleName)); - MOCK_METHOD2(BackupOnBundleFinished, void(int32_t errCode, string bundleName)); - MOCK_METHOD1(BackupOnAllBundlesFinished, void(int32_t errCode)); - MOCK_METHOD2(RestoreOnBundleStarted, void(int32_t errCode, std::string bundleName)); - MOCK_METHOD2(RestoreOnBundleFinished, void(int32_t errCode, string bundleName)); - MOCK_METHOD1(RestoreOnAllBundlesFinished, void(int32_t errCode)); - MOCK_METHOD3(RestoreOnFileReady, void(string bundleName, string fileName, int fd)); -}; - -class ServiceReverseStubTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override {}; - void TearDown() override {}; -}; - -/** - * @tc.number: SUB_backup_ServiceReverseStub_BackupOnFileReady_0100 - * @tc.name: SUB_backup_ServiceReverseStub_BackupOnFileReady_0100 - * @tc.desc: Test function of BackupOnFileReady interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, SUB_backup_ServiceReverseStub_BackupOnFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_BackupOnFileReady_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, BackupOnFileReady(_, _, _)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); - EXPECT_TRUE(data.WriteString(FILE_NAME)); - TestManager tm("ServiceReverseStub_0100"); - string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - data.WriteFileDescriptor(fd); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_BACKUP_ON_FILE_READY, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by BackupOnFileReady."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_BackupOnFileReady_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_BackupOnBundleStarted_0100 - * @tc.name: SUB_backup_ServiceReverseStub_BackupOnBundleStarted_0100 - * @tc.desc: Test function of BackupOnBundleStarted interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, - SUB_backup_ServiceReverseStub_BackupOnBundleStarted_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_BackupOnBundleStarted_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, BackupOnBundleStarted(_, _)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteInt32(BError(BError::Codes::OK))); - EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_BACKUP_ON_SUB_TASK_STARTED, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by BackupOnBundleStarted."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_BackupOnBundleStarted_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_BackupOnBundleFinished_0100 - * @tc.name: SUB_backup_ServiceReverseStub_BackupOnBundleFinished_0100 - * @tc.desc: Test function of BackupOnBundleFinished interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, - SUB_backup_ServiceReverseStub_BackupOnBundleFinished_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_BackupOnBundleFinished_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, BackupOnBundleFinished(_, _)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteInt32(BError(BError::Codes::OK))); - EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_BACKUP_ON_SUB_TASK_FINISHED, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by BackupOnBundleFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_BackupOnBundleFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_BackupOnAllBundlesFinished_0100 - * @tc.name: SUB_backup_ServiceReverseStub_BackupOnAllBundlesFinished_0100 - * @tc.desc: Test function of BackupOnAllBundlesFinished interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, - SUB_backup_ServiceReverseStub_BackupOnAllBundlesFinished_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_BackupOnAllBundlesFinished_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, BackupOnAllBundlesFinished(_)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteInt32(BError(BError::Codes::OK))); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_BACKUP_ON_TASK_FINISHED, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by BackupOnAllBundlesFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_BackupOnAllBundlesFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_RestoreOnBundleStarted_0100 - * @tc.name: SUB_backup_ServiceReverseStub_RestoreOnBundleStarted_0100 - * @tc.desc: Test function of RestoreOnBundleStarted interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, - SUB_backup_ServiceReverseStub_RestoreOnBundleStarted_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_RestoreOnBundleStarted_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, RestoreOnBundleStarted(_, _)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteInt32(BError(BError::Codes::OK))); - EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_RESTORE_ON_SUB_TASK_STARTED, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by RestoreOnBundleStarted."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_RestoreOnBundleStarted_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_RestoreOnBundleFinished_0100 - * @tc.name: SUB_backup_ServiceReverseStub_RestoreOnBundleFinished_0100 - * @tc.desc: Test function of RestoreOnBundleFinished interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, - SUB_backup_ServiceReverseStub_RestoreOnBundleFinished_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_RestoreOnBundleFinished_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, RestoreOnBundleFinished(_, _)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteInt32(BError(BError::Codes::OK))); - EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_RESTORE_ON_SUB_TASK_FINISHED, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by RestoreOnBundleFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_RestoreOnBundleFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_RestoreOnAllBundlesFinished_0100 - * @tc.name: SUB_backup_ServiceReverseStub_RestoreOnAllBundlesFinished_0100 - * @tc.desc: Test function of RestoreOnBundleStarted interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, - SUB_backup_ServiceReverseStub_RestoreOnAllBundlesFinished_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_RestoreOnAllBundlesFinished_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, RestoreOnAllBundlesFinished(_)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteInt32(BError(BError::Codes::OK))); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_RESTORE_ON_TASK_FINISHED, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by RestoreOnAllBundlesFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_RestoreOnAllBundlesFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_RestoreOnFileReady_0100 - * @tc.name: SUB_backup_ServiceReverseStub_RestoreOnFileReady_0100 - * @tc.desc: Test function of RestoreOnFileReady interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, SUB_backup_ServiceReverseStub_RestoreOnFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_RestoreOnFileReady_0100"; - try { - MockServiceReverse service; - EXPECT_CALL(service, RestoreOnFileReady(_, _, _)).WillOnce(Return()); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IServiceReverse::GetDescriptor())); - EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); - EXPECT_TRUE(data.WriteString(FILE_NAME)); - - TestManager tm("ServiceReverseStub_0200"); - string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - data.WriteFileDescriptor(fd); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_RESTORE_ON_FILE_READY, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred by RestoreOnFileReady."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_RestoreOnFileReady_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverseStub_error_0100 - * @tc.name: SUB_backup_ServiceReverseStub_error_0100 - * @tc.desc: Test function of RestoreOnFileReady interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseStubTest, SUB_backup_ServiceReverseStub_error_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseStubTest-begin SUB_backup_ServiceReverseStub_error_0100"; - try { - MockServiceReverse service; - MessageParcel data; - MessageParcel reply; - MessageOption option; - EXPECT_TRUE(data.WriteInterfaceToken(Str8ToStr16("test"))); - - EXPECT_NE(BError(BError::Codes::OK), service.OnRemoteRequest(3333, data, reply, option)); - EXPECT_NE(BError(BError::Codes::OK), - service.OnRemoteRequest(IServiceReverse::SERVICER_RESTORE_ON_FILE_READY, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseStubTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "ServiceReverseStubTest-end SUB_backup_ServiceReverseStub_error_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/service_reverse_test.cpp b/tests/unittests/backup_api/backup_impl/service_reverse_test.cpp deleted file mode 100644 index 85e949400..000000000 --- a/tests/unittests/backup_api/backup_impl/service_reverse_test.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_session_restore.h" -#include "refbase.h" -#include "service_reverse.h" -#include "test_manager.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -const string FILE_NAME = "1.tar"; -} // namespace - -class ServiceReverseTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override {}; - void TearDown() override; - - void Init(IServiceReverse::Scenario scenario, int nType = 0); - sptr service_ = nullptr; -}; - -static void OnFileReadyTest(const BFileInfo &fileInfo, UniqueFd fd) -{ - EXPECT_EQ(fileInfo.owner, BUNDLE_NAME); - EXPECT_EQ(fileInfo.fileName, FILE_NAME); - GTEST_LOG_(INFO) << "ServiceReverseTest-OnFileReadyTest SUCCESS"; -} - -static void OnBundleStartedTest(ErrCode err, const BundleName name) -{ - EXPECT_EQ(name, BUNDLE_NAME); - GTEST_LOG_(INFO) << "ServiceReverseTest-OnBundleStartedTest SUCCESS"; -} - -static void OnBundleFinishedTest(ErrCode err, const BundleName name) -{ - EXPECT_EQ(name, BUNDLE_NAME); - GTEST_LOG_(INFO) << "ServiceReverseTest-OnBundleFinishedTest SUCCESS"; -} - -static void OnAllBundlesFinishedTest(ErrCode err) -{ - EXPECT_EQ(err, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceReverseTest-OnAllBundlesFinishedTest SUCCESS"; -} - -static void OnBackupServiceDiedTest() {} - -void ServiceReverseTest::TearDown() -{ - service_ = nullptr; -} - -void ServiceReverseTest::Init(IServiceReverse::Scenario scenario, int nType) -{ - if (scenario == IServiceReverse::Scenario::BACKUP) { - if (nType) { - service_ = new ServiceReverse(BSessionBackup::Callbacks {.onFileReady = nullptr, - .onBundleStarted = nullptr, - .onBundleFinished = nullptr, - .onAllBundlesFinished = nullptr, - .onBackupServiceDied = nullptr}); - } else { - service_ = new ServiceReverse(BSessionBackup::Callbacks { - .onFileReady = bind(OnFileReadyTest, placeholders::_1, placeholders::_2), - .onBundleStarted = bind(OnBundleStartedTest, placeholders::_1, placeholders::_2), - .onBundleFinished = bind(OnBundleFinishedTest, placeholders::_1, placeholders::_2), - .onAllBundlesFinished = bind(OnAllBundlesFinishedTest, placeholders::_1), - .onBackupServiceDied = bind(OnBackupServiceDiedTest)}); - } - } else { - if (nType) { - service_ = new ServiceReverse(BSessionRestore::Callbacks {.onFileReady = nullptr, - .onBundleStarted = nullptr, - .onBundleFinished = nullptr, - .onAllBundlesFinished = nullptr, - .onBackupServiceDied = nullptr}); - } else { - service_ = new ServiceReverse(BSessionRestore::Callbacks { - .onFileReady = bind(OnFileReadyTest, placeholders::_1, placeholders::_2), - .onBundleStarted = bind(OnBundleStartedTest, placeholders::_1, placeholders::_2), - .onBundleFinished = bind(OnBundleFinishedTest, placeholders::_1, placeholders::_2), - .onAllBundlesFinished = bind(OnAllBundlesFinishedTest, placeholders::_1), - .onBackupServiceDied = bind(OnBackupServiceDiedTest)}); - } - } -} - -/** - * @tc.number: SUB_backup_ServiceReverse_BackupOnFileReady_0100 - * @tc.name: SUB_backup_ServiceReverse_BackupOnFileReady_0100 - * @tc.desc: 测试 BackupOnFileReady 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_BackupOnFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_BackupOnFileReady_0100"; - try { - Init(IServiceReverse::Scenario::BACKUP); - service_->BackupOnFileReady(BUNDLE_NAME, FILE_NAME, -1); - service_->RestoreOnFileReady(BUNDLE_NAME, FILE_NAME, -1); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by BackupOnFileReady."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_BackupOnFileReady_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_BackupOnBundleStarted_0100 - * @tc.name: SUB_backup_ServiceReverse_BackupOnBundleStarted_0100 - * @tc.desc: 测试 BackupOnBundleStarted 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_BackupOnBundleStarted_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_BackupOnBundleStarted_0100"; - try { - Init(IServiceReverse::Scenario::BACKUP); - service_->BackupOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - service_->RestoreOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by BackupOnBundleStarted."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_BackupOnBundleStarted_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_BackupOnBundleFinished_0100 - * @tc.name: SUB_backup_ServiceReverse_BackupOnBundleFinished_0100 - * @tc.desc: 测试 BackupOnBundleFinished 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_BackupOnBundleFinished_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_BackupOnBundleFinished_0100"; - try { - Init(IServiceReverse::Scenario::BACKUP); - service_->BackupOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - service_->RestoreOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by BackupOnBundleFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_BackupOnBundleFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_BackupOnAllBundlesFinished_0100 - * @tc.name: SUB_backup_ServiceReverse_BackupOnAllBundlesFinished_0100 - * @tc.desc: 测试 BackupOnAllBundlesFinished 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_BackupOnAllBundlesFinished_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_BackupOnAllBundlesFinished_0100"; - try { - Init(IServiceReverse::Scenario::BACKUP); - service_->BackupOnAllBundlesFinished(BError(BError::Codes::OK)); - service_->RestoreOnAllBundlesFinished(BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by BackupOnAllBundlesFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_BackupOnAllBundlesFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_RestoreOnFileReady_0100 - * @tc.name: SUB_backup_ServiceReverse_RestoreOnFileReady_0100 - * @tc.desc: 测试 RestoreOnFileReady 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_RestoreOnFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_RestoreOnFileReady_0100"; - try { - Init(IServiceReverse::Scenario::RESTORE); - service_->RestoreOnFileReady(BUNDLE_NAME, FILE_NAME, -1); - service_->BackupOnFileReady(BUNDLE_NAME, FILE_NAME, -1); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by RestoreOnFileReady."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_RestoreOnFileReady_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_RestoreOnBundleStarted_0100 - * @tc.name: SUB_backup_ServiceReverse_RestoreOnBundleStarted_0100 - * @tc.desc: 测试 RestoreOnBundleStarted 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_RestoreOnBundleStarted_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_RestoreOnBundleStarted_0100"; - try { - Init(IServiceReverse::Scenario::RESTORE); - service_->RestoreOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - service_->BackupOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by RestoreOnBundleStarted."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_RestoreOnBundleStarted_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_RestoreOnBundleFinished_0100 - * @tc.name: SUB_backup_ServiceReverse_RestoreOnBundleFinished_0100 - * @tc.desc: 测试 RestoreOnBundleFinished 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_RestoreOnBundleFinished_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_RestoreOnBundleFinished_0100"; - try { - Init(IServiceReverse::Scenario::RESTORE); - service_->RestoreOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - service_->BackupOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by RestoreOnBundleFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_RestoreOnBundleFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_RestoreOnAllBundlesFinished_0100 - * @tc.name: SUB_backup_ServiceReverse_RestoreOnAllBundlesFinished_0100 - * @tc.desc: 测试 RestoreOnAllBundlesFinished 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_RestoreOnAllBundlesFinished_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_RestoreOnAllBundlesFinished_0100"; - try { - Init(IServiceReverse::Scenario::RESTORE); - service_->RestoreOnAllBundlesFinished(BError(BError::Codes::OK)); - service_->BackupOnAllBundlesFinished(BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred by RestoreOnAllBundlesFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_RestoreOnAllBundlesFinished_0100"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_0200 - * @tc.name: SUB_backup_ServiceReverse_0200 - * @tc.desc: 测试分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_0200"; - try { - Init(IServiceReverse::Scenario::RESTORE, 1); - service_->RestoreOnFileReady(BUNDLE_NAME, FILE_NAME, -1); - service_->RestoreOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - service_->RestoreOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - service_->RestoreOnAllBundlesFinished(BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_0200"; -} - -/** - * @tc.number: SUB_backup_ServiceReverse_0300 - * @tc.name: SUB_backup_ServiceReverse_0300 - * @tc.desc: 测试分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseTest, SUB_backup_ServiceReverse_0300, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseTest-begin SUB_backup_ServiceReverse_0300"; - try { - Init(IServiceReverse::Scenario::BACKUP, 1); - service_->BackupOnFileReady(BUNDLE_NAME, FILE_NAME, -1); - service_->BackupOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - service_->BackupOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - service_->BackupOnAllBundlesFinished(BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "ServiceReverseTest-end SUB_backup_ServiceReverse_0300"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/svc_death_recipient_test.cpp b/tests/unittests/backup_api/backup_impl/svc_death_recipient_test.cpp deleted file mode 100644 index 27cca4655..000000000 --- a/tests/unittests/backup_api/backup_impl/svc_death_recipient_test.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "iservice_registry.h" -#include "service_reverse_mock.h" -#include "svc_death_recipient.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -const string FILE_NAME = "temp.json"; - -class SvcDeathRecipientTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override {}; - void TearDown() override {}; -}; - -static void CallBack(const wptr &obj) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-CallBack success"; -} - -/** - * @tc.number: SUB_backup_sa_deathecipient_OnRemoteDied_0100 - * @tc.name: SUB_backup_sa_deathecipient_OnRemoteDied_0100 - * @tc.desc: 测试 OnRemoteDied 接口调用成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcDeathRecipientTest, SUB_backup_sa_deathecipient_OnRemoteDied_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_deathecipient_OnRemoteDied_0100"; - sptr remote = sptr(new ServiceReverseMock()); - sptr deathRecipient = sptr(new SvcDeathRecipient(CallBack)); - remote->AddDeathRecipient(deathRecipient); - deathRecipient->OnRemoteDied(remote); - remote = nullptr; - deathRecipient = nullptr; - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_deathecipient_OnRemoteDied_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/BUILD.gn b/tests/unittests/backup_sa/BUILD.gn deleted file mode 100644 index 45559f172..000000000 --- a/tests/unittests/backup_sa/BUILD.gn +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -group("backup_sa_test") { - testonly = true - - deps = [ "module_ipc:backup_sa_ipc_test" ] -} diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn deleted file mode 100644 index 14d50d98c..000000000 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ /dev/null @@ -1,175 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_unittest("module_ipc_test") { - module_out_path = path_module_out_tests - - sources = [ - "service_reverse_proxy_test.cpp", - "service_stub_test.cpp", - "svc_backup_connection_test.cpp", - "svc_extension_proxy_test.cpp", - ] - - include_dirs = [ - "${path_backup}/services/backup_sa/include", - "${path_base}/include", - "${path_backup}/tests/unittests/backup_api/backup_impl/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - ] - - deps = [ - "${path_backup}/services/backup_sa:backup_sa", - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - "//third_party/googletest:gmock_main", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "app_file_service:backup_kit_inner", - "c_utils:utils", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - - use_exceptions = true -} - -ohos_unittest("backup_service_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup_mock}/accesstoken/accesstoken_kit_mock.cpp", - "${path_backup}/services/backup_sa/src/module_ipc/service.cpp", - "service_test.cpp", - ] - sources += backup_mock_src - sources += backup_mock_session_manager_src - sources += backup_mock_scheduler_src - - include_dirs = [ - "${path_backup}/services/backup_sa/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - "${path_backup}/tests/unittests/backup_api/backup_impl/include", - "${path_access_token}/interfaces/innerkits/accesstoken/include", - "${path_backup_mock}/b_process/", - ] - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - "${path_googletest}:gmock_main", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "app_file_service:backup_kit_inner", - "init:libbegetutil", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - - use_exceptions = true -} - -ohos_unittest("backup_service_session_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup_mock}/affwk/service_registry_mock.cpp", - "${path_backup_mock}/bundle_manager/src/mock_bundle_manager.cpp", - "${path_backup}/services/backup_sa/src/module_ipc/svc_session_manager.cpp", - "svc_session_manager_test.cpp", - ] - sources += backup_mock_src - sources += backup_mock_scheduler_src - sources += backup_mock_service_src - - include_dirs = [ - "${path_backup}/services/backup_sa/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - "${path_backup}/tests/unittests/backup_api/backup_impl/include", - "${path_base}/include", - "${path_backup_mock}/bundle_manager/include", - ] - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - "${path_googletest}:gmock_main", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "app_file_service:backup_kit_inner", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - - use_exceptions = true -} - -ohos_unittest("backup_service_scheduler_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup_mock}/timer/timer_mock.cpp", - "${path_backup}/services/backup_sa/src/module_sched/sched_scheduler.cpp", - "sched_scheduler_test.cpp", - ] - sources += backup_mock_src - sources += backup_mock_service_src - sources += backup_mock_session_manager_src - - include_dirs = [ - "${path_backup}/services/backup_sa/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - "${path_backup}/tests/unittests/backup_api/backup_impl/include", - ] - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - "${path_googletest}:gmock_main", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "app_file_service:backup_kit_inner", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - ] - - use_exceptions = true -} - -group("backup_sa_ipc_test") { - testonly = true - deps = [ - ":backup_service_scheduler_test", - ":backup_service_session_test", - ":backup_service_test", - ":module_ipc_test", - ] -} diff --git a/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp b/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp deleted file mode 100644 index 1e7a939e8..000000000 --- a/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include - -#include - -#include "b_error/b_error.h" -#include "module_ipc/service.h" -#include "module_ipc/svc_session_manager.h" -#include "module_sched/sched_scheduler.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -constexpr int32_t CLIENT_TOKEN_ID = 100; -constexpr int32_t SERVICE_ID = 5203; -constexpr int32_t WAIT_TIME = 3; -} // namespace - -class SchedSchedulerTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(); - void SetUp() override {}; - void TearDown() override {}; - void Init(IServiceReverse::Scenario scenario); - - static inline sptr schedPtr_ = nullptr; - static inline sptr sessionManagerPtr_ = nullptr; - static inline sptr servicePtr_ = nullptr; -}; - -void SchedSchedulerTest::SetUpTestCase() -{ - servicePtr_ = sptr(new Service(SERVICE_ID)); - sessionManagerPtr_ = sptr(new SvcSessionManager(wptr(servicePtr_))); - schedPtr_ = sptr(new SchedScheduler(wptr(servicePtr_), wptr(sessionManagerPtr_))); -} - -void SchedSchedulerTest::TearDownTestCase() -{ - schedPtr_ = nullptr; - servicePtr_ = nullptr; - sessionManagerPtr_ = nullptr; -} - -void SchedSchedulerTest::Init(IServiceReverse::Scenario scenario) -{ - vector bundleNames; - map backupExtNameMap; - bundleNames.emplace_back(BUNDLE_NAME); - auto setBackupExtNameMap = [](const string &bundleName) { - BackupExtInfo info {}; - info.backupExtName = BUNDLE_NAME; - info.receExtManageJson = true; - info.receExtAppDone = true; - return make_pair(bundleName, info); - }; - transform(bundleNames.begin(), bundleNames.end(), inserter(backupExtNameMap, backupExtNameMap.end()), - setBackupExtNameMap); - - sessionManagerPtr_->Active({ - .clientToken = CLIENT_TOKEN_ID, - .scenario = scenario, - .backupExtNameMap = move(backupExtNameMap), - }); -} - -/** - * @tc.number: SUB_Service_Sched_0100 - * @tc.name: SUB_Service_Sched_0100 - * @tc.desc: 测试 Sched接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SchedSchedulerTest, SUB_Service_Sched_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_Sched_0100"; - try { - Init(IServiceReverse::Scenario::BACKUP); - schedPtr_->Sched(); - GTEST_LOG_(INFO) << "SchedSchedulerTest-Sched Branches"; - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::FINISH); - schedPtr_->Sched(); - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::WAIT); - schedPtr_->Sched(); - GTEST_LOG_(INFO) << "SchedSchedulerTest-ExecutingQueueTasks time callback"; - schedPtr_->RemoveExtConn(BUNDLE_NAME); - schedPtr_->Sched("test"); - // SchedScheduler在析构时释放OHOS::ThreadPool若此时没有完成的任务,ThreadPool在析构调用stop时会出现异常,目前暂时sleep处理,后续更改ThreadPool方案 - // 原因是sleep等待ThreadPool任务完成后,任务不再额外持有SchedScheduler的引用计数 - // 于是本函数执行结束后SchedScheduler引用计数清空,得以在另外的线程上析构SchedScheduler对象及其中的线程池。 - sleep(WAIT_TIME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by Sched."; - } - GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_Sched_0100"; -} - -/** - * @tc.number: SUB_Service_ExecutingQueueTasks_0100 - * @tc.name: SUB_Service_ExecutingQueueTasks_0100 - * @tc.desc: 测试 ExecutingQueueTasks 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SchedSchedulerTest, SUB_Service_ExecutingQueueTasks_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_ExecutingQueueTasks_0100"; - try { - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::START); - schedPtr_->ExecutingQueueTasks(BUNDLE_NAME); - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::RUNNING); - schedPtr_->ExecutingQueueTasks(BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by ExecutingQueueTasks."; - } - GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_ExecutingQueueTasks_0100"; -} - -/** - * @tc.number: SUB_Service_RemoveExtConn_0100 - * @tc.name: SUB_Service_RemoveExtConn_0100 - * @tc.desc: 测试 RemoveExtConn 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SchedSchedulerTest, SUB_Service_RemoveExtConn_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_RemoveExtConn_0100"; - try { - schedPtr_->RemoveExtConn("test"); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by RemoveExtConn."; - } - GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_RemoveExtConn_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp deleted file mode 100644 index 66d9d6f43..000000000 --- a/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_file_info.h" -#include "iservice_registry.h" -#include "module_ipc/service_reverse_proxy.h" -#include "service_reverse_mock.h" -#include "test_manager.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -const string FILE_NAME = "1.tar"; -} // namespace - -class ServiceReverseProxyTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override; - void TearDown() override; - shared_ptr proxy_ = nullptr; - sptr mock_ = nullptr; -}; - -void ServiceReverseProxyTest::SetUp() -{ - mock_ = sptr(new ServiceReverseMock()); - proxy_ = make_shared(mock_); -} -void ServiceReverseProxyTest::TearDown() -{ - mock_ = nullptr; - proxy_ = nullptr; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_BackupOnFileReady_0100 - * @tc.name: SUB_ServiceReverse_proxy_BackupOnFileReady_0100 - * @tc.desc: Test function of BackupOnFileReady interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_BackupOnFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_BackupOnFileReady_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - - TestManager tm("ServiceReverseProxyTest_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - proxy_->BackupOnFileReady(BUNDLE_NAME, FILE_NAME, fd); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by BackupOnFileReady."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_BackupOnFileReady_0100"; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_BackupOnBundleStarted_0100 - * @tc.name: SUB_ServiceReverse_proxy_BackupOnBundleStarted_0100 - * @tc.desc: Test function of BackupOnBundleStarted interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_BackupOnBundleStarted_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_BackupOnBundleStarted_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - proxy_->BackupOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by BackupOnBundleStarted."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_BackupOnBundleStarted_0100"; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_BackupOnBundleFinished_0100 - * @tc.name: SUB_ServiceReverse_proxy_BackupOnBundleFinished_0100 - * @tc.desc: Test function of BackupOnBundleFinished interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_BackupOnBundleFinished_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_BackupOnBundleFinished_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - proxy_->BackupOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by BackupOnBundleFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_BackupOnBundleFinished_0100"; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_BackupOnAllBundlesFinished_0100 - * @tc.name: SUB_ServiceReverse_proxy_BackupOnAllBundlesFinished_0100 - * @tc.desc: Test function of BackupOnAllBundlesFinished interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, - SUB_ServiceReverse_proxy_BackupOnAllBundlesFinished_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_BackupOnAllBundlesFinished_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - proxy_->BackupOnAllBundlesFinished(BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by BackupOnAllBundlesFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_BackupOnAllBundlesFinished_0100"; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_RestoreOnBundleStarted_0100 - * @tc.name: SUB_ServiceReverse_proxy_RestoreOnBundleStarted_0100 - * @tc.desc: Test function of RestoreOnBundleStarted interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_RestoreOnBundleStarted_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_RestoreOnBundleStarted_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - proxy_->RestoreOnBundleStarted(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by RestoreOnBundleStarted."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_RestoreOnBundleStarted_0100"; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_RestoreOnBundleFinished_0100 - * @tc.name: SUB_ServiceReverse_proxy_RestoreOnBundleFinished_0100 - * @tc.desc: Test function of RestoreOnBundleFinished interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_RestoreOnBundleFinished_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_RestoreOnBundleFinished_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - proxy_->RestoreOnBundleFinished(BError(BError::Codes::OK), BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by RestoreOnBundleFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_RestoreOnBundleFinished_0100"; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_RestoreOnAllBundlesFinished_0100 - * @tc.name: SUB_ServiceReverse_proxy_RestoreOnAllBundlesFinished_0100 - * @tc.desc: Test function of RestoreOnAllBundlesFinished interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, - SUB_ServiceReverse_proxy_RestoreOnAllBundlesFinished_0100, - testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_RestoreOnAllBundlesFinished_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - proxy_->RestoreOnAllBundlesFinished(BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by RestoreOnAllBundlesFinished."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_RestoreOnAllBundlesFinished_0100"; -} - -/** - * @tc.number: SUB_ServiceReverse_proxy_RestoreOnFileReady_0100 - * @tc.name: SUB_ServiceReverse_proxy_RestoreOnFileReady_0100 - * @tc.desc: Test function of RestoreOnFileReady interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_RestoreOnFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_RestoreOnFileReady_0100"; - try { - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(1) - .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); - - TestManager tm("ServiceReverseProxyTest_GetFd_0200"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - proxy_->RestoreOnFileReady(BUNDLE_NAME, FILE_NAME, fd); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by RestoreOnFileReady."; - } - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_RestoreOnFileReady_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp deleted file mode 100644 index 8a982e086..000000000 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "i_service.h" -#include "module_ipc/service_stub.h" -#include "service_reverse_mock.h" -#include "test_manager.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -const string FILE_NAME = "1.tar"; -} // namespace - -class MockService final : public ServiceStub { -public: - MOCK_METHOD2(InitRestoreSession, ErrCode(sptr remote, const vector &bundleNames)); - MOCK_METHOD3(InitBackupSession, - ErrCode(sptr remote, UniqueFd fd, const vector &bundleNames)); - MOCK_METHOD0(Start, ErrCode()); - MOCK_METHOD0(GetLocalCapabilities, UniqueFd()); - MOCK_METHOD1(PublishFile, ErrCode(const BFileInfo &fileInfo)); - MOCK_METHOD2(AppFileReady, ErrCode(const string &fileName, UniqueFd fd)); - MOCK_METHOD1(AppDone, ErrCode(ErrCode errCode)); - MOCK_METHOD2(GetExtFileName, ErrCode(string &bundleName, string &fileName)); - UniqueFd InvokeGetLocalCapabilities() - { - if (bCapabilities_) { - return UniqueFd(-1); - } - TestManager tm("MockService_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - bCapabilities_ = true; - return fd; - } - -private: - bool bCapabilities_ = {false}; -}; - -class ServiceStubTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override {}; - void TearDown() override {}; -}; - -/** - * @tc.number: SUB_backup_sa_ServiceStub_InitRestoreSession_0100 - * @tc.name: SUB_backup_sa_ServiceStub_InitRestoreSession_0100 - * @tc.desc: Test function of InitRestoreSession interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_InitRestoreSession_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_InitRestoreSession_0100"; - try { - MockService service; - EXPECT_CALL(service, InitRestoreSession(_, _)).WillOnce(Return(BError(BError::Codes::OK))); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - sptr remote = sptr(new ServiceReverseMock()); - EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); - vector bundleNames; - bundleNames.push_back(BUNDLE_NAME); - EXPECT_TRUE(data.WriteStringVector(bundleNames)); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_INIT_RESTORE_SESSION, data, reply, option)); - remote = nullptr; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by InitRestoreSession."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_InitRestoreSession_0100"; -} - -/** - * @tc.number: SUB_backup_sa_ServiceStub_InitBackupSession_0100 - * @tc.name: SUB_backup_sa_ServiceStub_InitBackupSession_0100 - * @tc.desc: Test function of InitBackupSession interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_InitBackupSession_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_InitBackupSession_0100"; - try { - MockService service; - EXPECT_CALL(service, InitBackupSession(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - vector bundleNames; - bundleNames.push_back(BUNDLE_NAME); - sptr remote = sptr(new ServiceReverseMock()); - TestManager tm("ServiceStub_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); - EXPECT_TRUE(data.WriteFileDescriptor(fd)); - EXPECT_TRUE(data.WriteStringVector(bundleNames)); - - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_INIT_BACKUP_SESSION, data, reply, option)); - GTEST_LOG_(INFO) << "ServiceStubTest-CmdInitBackupSession Brances"; - MessageParcel brances; - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); - EXPECT_NE(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_INIT_BACKUP_SESSION, brances, reply, option)); - remote = nullptr; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by InitBackupSession."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_InitBackupSession_0100"; -} - -/** - * @tc.number: SUB_backup_sa_ServiceStub_Start_0100 - * @tc.name: SUB_backup_sa_ServiceStub_Start_0100 - * @tc.desc: Test function of Start interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_Start_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_Start_0100"; - try { - MockService service; - EXPECT_CALL(service, Start()).WillOnce(Return(BError(BError::Codes::OK))); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_EQ(BError(BError::Codes::OK), service.OnRemoteRequest(IService::SERVICE_CMD_START, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by Start."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_Start_0100"; -} - -/** - * @tc.number: SUB_backup_sa_ServiceStub_GetLocalCapabilities_0100 - * @tc.name: SUB_backup_sa_ServiceStub_GetLocalCapabilities_0100 - * @tc.desc: Test function of GetLocalCapabilities interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_GetLocalCapabilities_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_GetLocalCapabilities_0100"; - try { - sptr serviceSptr = sptr(new MockService()); - EXPECT_CALL(*serviceSptr, GetLocalCapabilities()) - .Times(2) - .WillOnce(Invoke(serviceSptr.GetRefPtr(), &MockService::InvokeGetLocalCapabilities)) - .WillOnce(Invoke(serviceSptr.GetRefPtr(), &MockService::InvokeGetLocalCapabilities)); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - - EXPECT_EQ(BError(BError::Codes::OK), - serviceSptr->OnRemoteRequest(IService::SERVICE_CMD_GET_LOCAL_CAPABILITIES, data, reply, option)); - UniqueFd fd(reply.ReadFileDescriptor()); - EXPECT_GT(fd, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceStubTest-CmdGetLocalCapabilities Brances"; - MessageParcel brances; - EXPECT_TRUE(brances.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_NE(BError(BError::Codes::OK), - serviceSptr->OnRemoteRequest(IService::SERVICE_CMD_GET_LOCAL_CAPABILITIES, brances, reply, option)); - serviceSptr = nullptr; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by GetLocalCapabilities."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_GetLocalCapabilities_0100"; -} - -/** - * @tc.number: SUB_backup_sa_ServiceStub_PublishFile_0100 - * @tc.name: SUB_backup_sa_ServiceStub_PublishFile_0100 - * @tc.desc: Test function of PublishFile interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_PublishFile_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_PublishFile_0100"; - try { - MockService service; - EXPECT_CALL(service, PublishFile(_)).WillOnce(Return(BError(BError::Codes::OK))); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - BFileInfo fileInfo {BUNDLE_NAME, FILE_NAME, -1}; - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(data.WriteParcelable(&fileInfo)); - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_PUBLISH_FILE, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by PublishFile."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_PublishFile_0100"; -} - -/** - * @tc.number: SUB_backup_sa_ServiceStub_AppFileReady_0100 - * @tc.name: SUB_backup_sa_ServiceStub_AppFileReady_0100 - * @tc.desc: Test function of AppFileReady interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_AppFileReady_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_AppFileReady_0100"; - try { - MockService service; - EXPECT_CALL(service, AppFileReady(_, _)).WillOnce(Return(BError(BError::Codes::OK))); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - TestManager tm("ServiceStub_GetFd_0200"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(data.WriteString(FILE_NAME)); - EXPECT_TRUE(data.WriteFileDescriptor(fd)); - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_APP_FILE_READY, data, reply, option)); - GTEST_LOG_(INFO) << "ServiceStubTest-begin-CmdAppFileReady Brances"; - MessageParcel brances; - EXPECT_TRUE(brances.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(brances.WriteString(FILE_NAME)); - EXPECT_NE(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_APP_FILE_READY, brances, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by AppFileReady."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_AppFileReady_0100"; -} - -/** - * @tc.number: SUB_backup_sa_ServiceStub_AppDone_0100 - * @tc.name: SUB_backup_sa_ServiceStub_AppDone_0100 - * @tc.desc: Test function of AppDone interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_AppDone_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_AppDone_0100"; - try { - MockService service; - EXPECT_CALL(service, AppDone(_)).WillOnce(Return(BError(BError::Codes::OK))); - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(data.WriteInt32(BError(BError::Codes::OK))); - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_APP_DONE, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by AppDone."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_AppDone_0100"; -} - -/** - * @tc.number: SUB_backup_sa_ServiceStub_GetExtFileName_0100 - * @tc.name: SUB_backup_sa_ServiceStub_GetExtFileName_0100 - * @tc.desc: Test function of GetExtFileName interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_GetExtFileName_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_GetExtFileName_0100"; - try { - MockService service; - EXPECT_CALL(service, GetExtFileName(_, _)).WillOnce(Return(BError(BError::Codes::OK))); - MessageParcel data; - MessageParcel reply; - MessageOption option; - option.SetFlags(MessageOption::TF_ASYNC); - - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); - EXPECT_TRUE(data.WriteString(FILE_NAME)); - EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_GET_EXT_FILE_NAME, data, reply, option)); - EXPECT_NE(BError(BError::Codes::OK), service.OnRemoteRequest(3333, data, reply, option)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by GetExtFileName."; - } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_GetExtFileName_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp deleted file mode 100644 index 6e621555d..000000000 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include - -#include "module_ipc/service.h" -#include "service_reverse_mock.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -const string MANAGE_JSON = "manage.json"; -const string FILE_NAME = "1.tar"; -constexpr int32_t SERVICE_ID = 5203; -} // namespace - -class ServiceTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(); - void SetUp() {}; - void TearDown() {}; - - ErrCode Init(IServiceReverse::Scenario scenario); - - static inline sptr servicePtr_ = nullptr; - static inline sptr remote_ = nullptr; -}; - -void ServiceTest::SetUpTestCase(void) -{ - GTEST_LOG_(INFO) << "SetUpTestCase enter"; - servicePtr_ = sptr(new Service(SERVICE_ID)); - remote_ = sptr(new ServiceReverseMock()); -} - -void ServiceTest::TearDownTestCase() -{ - GTEST_LOG_(INFO) << "TearDownTestCase enter"; - servicePtr_ = nullptr; - remote_ = nullptr; -} - -ErrCode ServiceTest::Init(IServiceReverse::Scenario scenario) -{ - vector bundleNames; - bundleNames.emplace_back(BUNDLE_NAME); - ErrCode ret = 0; - if (scenario == IServiceReverse::Scenario::RESTORE) { - ret = servicePtr_->InitRestoreSession(remote_, bundleNames); - } else if (scenario == IServiceReverse::Scenario::BACKUP) { - UniqueFd fd = servicePtr_->GetLocalCapabilities(); - EXPECT_GT(fd, BError(BError::Codes::OK)); - ret = servicePtr_->InitBackupSession(remote_, move(fd), bundleNames); - } - return ret; -} - -/** - * @tc.number: SUB_Service_GetLocalCapabilities_0100 - * @tc.name: SUB_Service_GetLocalCapabilities_0100 - * @tc.desc: 测试 GetLocalCapabilities 获取本地能力文件 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_GetLocalCapabilities_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetLocalCapabilities_0100"; - try { - UniqueFd fd = servicePtr_->GetLocalCapabilities(); - EXPECT_GT(fd, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetLocalCapabilities."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetLocalCapabilities_0100"; -} - -/** - * @tc.number: SUB_Service_OnStart_0100 - * @tc.name: SUB_Service_OnStart_0100 - * @tc.desc: 测试 OnStart 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_OnStart_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnStart_0100"; - try { - servicePtr_->OnStart(); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by OnStart."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnStart_0100"; -} - -/** - * @tc.number: SUB_Service_Start_0100 - * @tc.name: SUB_Service_Start_0100 - * @tc.desc: 测试 Start 备份恢复启动 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_Start_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_Start_0100"; - try { - auto ret = servicePtr_->Start(); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by Start."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_Start_0100"; -} - -/** - * @tc.number: SUB_Service_PublishFile_0100 - * @tc.name: SUB_Service_PublishFile_0100 - * @tc.desc: 测试 PublishFile 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_PublishFile_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_PublishFile_0100"; - try { - ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - BFileInfo fileInfo {BUNDLE_NAME, FILE_NAME, 0}; - ret = servicePtr_->PublishFile(fileInfo); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceTest-PublishFile Branches"; - fileInfo.fileName = "test"; - ret = servicePtr_->PublishFile(fileInfo); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by PublishFile."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_PublishFile_0100"; -} - -/** - * @tc.number: SUB_Service_AppFileReady_0100 - * @tc.name: SUB_Service_AppFileReady_0100 - * @tc.desc: 测试 AppFileReady 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_AppFileReady_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_AppFileReady_0100"; - try { - string fileName = MANAGE_JSON; - auto ret = servicePtr_->AppFileReady(fileName, UniqueFd(-1)); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceTest-AppFileReady Branches"; - fileName = "test"; - ret = servicePtr_->AppFileReady(fileName, UniqueFd(-1)); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by AppFileReady."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppFileReady_0100"; -} - -/** - * @tc.number: SUB_Service_AppDone_0100 - * @tc.name: SUB_Service_AppDone_0100 - * @tc.desc: 测试 AppDone 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_AppDone_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_AppDone_0100"; - try { - GTEST_LOG_(INFO) << "SUB_Service_AppDone_0100 RESTORE"; - auto ret = servicePtr_->AppDone(BError(BError::Codes::OK)); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SUB_Service_AppDone_0100 BACKUP"; - ret = Init(IServiceReverse::Scenario::BACKUP); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceTest-AppDone Branches"; - ret = servicePtr_->AppDone(1); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceTest-AppDone Branches End"; - ret = servicePtr_->AppDone(BError(BError::Codes::OK)); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by AppDone."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppDone_0100"; -} - -/** - * @tc.number: SUB_Service_LaunchBackupExtension_0100 - * @tc.name: SUB_Service_LaunchBackupExtension_0100 - * @tc.desc: 测试 LaunchBackupExtension 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_LaunchBackupExtension_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_LaunchBackupExtension_0100"; - try { - GTEST_LOG_(INFO) << "SUB_Service_LaunchBackupExtension_0100 RESTORE"; - ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - ret = servicePtr_->LaunchBackupExtension(BUNDLE_NAME); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SUB_Service_LaunchBackupExtension_0100 BACKUP"; - ret = Init(IServiceReverse::Scenario::BACKUP); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - ret = servicePtr_->LaunchBackupExtension(BUNDLE_NAME); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by LaunchBackupExtension."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_LaunchBackupExtension_0100"; -} - -/** - * @tc.number: SUB_Service_GetExtFileName_0100 - * @tc.name: SUB_Service_GetExtFileName_0100 - * @tc.desc: 测试 GetExtFileName 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_GetExtFileName_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetExtFileName_0100"; - try { - ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - - string bundleName = BUNDLE_NAME; - string fileName = FILE_NAME; - ret = servicePtr_->GetExtFileName(bundleName, fileName); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetExtFileName."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetExtFileName_0100"; -} - -/** - * @tc.number: SUB_Service_OnBackupExtensionDied_0100 - * @tc.name: SUB_Service_OnBackupExtensionDied_0100 - * @tc.desc: 测试 OnBackupExtensionDied 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_OnBackupExtensionDied_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnBackupExtensionDied_0100"; - try { - GTEST_LOG_(INFO) << "SUB_Service_OnBackupExtensionDied_0100 RESTORE"; - ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - string bundleName = BUNDLE_NAME; - servicePtr_->OnBackupExtensionDied(move(bundleName), BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SUB_Service_OnBackupExtensionDied_0100 BACKUP"; - ret = Init(IServiceReverse::Scenario::BACKUP); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - bundleName = BUNDLE_NAME; - servicePtr_->OnBackupExtensionDied(move(bundleName), BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetExtFileName."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBackupExtensionDied_0100"; -} - -/** - * @tc.number: SUB_Service_ExtStart_0100 - * @tc.name: SUB_Service_ExtStart_0100 - * @tc.desc: 测试 ExtStart 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_ExtStart_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ExtStart_0100"; - try { - GTEST_LOG_(INFO) << "SUB_Service_ExtStart_0100 BACKUP"; - ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - servicePtr_->ExtStart(BUNDLE_NAME); - GTEST_LOG_(INFO) << "ServiceTest-ExtStart BACKUP Branches"; - servicePtr_->ExtStart(BUNDLE_NAME); - GTEST_LOG_(INFO) << "SUB_Service_ExtStart_0100 RESTORE"; - ret = Init(IServiceReverse::Scenario::RESTORE); - servicePtr_->ExtStart(BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtStart."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtStart_0100"; -} - -/** - * @tc.number: SUB_Service_Dump_0100 - * @tc.name: SUB_Service_Dump_0100 - * @tc.desc: 测试 Dump 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_Dump_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_Dump_0100"; - try { - servicePtr_->Dump(-1, {}); - TestManager tm("ServiceTest_GetFd_0100"); - string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - servicePtr_->Dump(move(fd), {}); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by Dump."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_Dump_0100"; -} - -/** - * @tc.number: SUB_Service_ExtConnectFailed_0100 - * @tc.name: SUB_Service_ExtConnectFailed_0100 - * @tc.desc: 测试 ExtConnectFailed 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_ExtConnectFailed_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ExtConnectFailed_0100"; - try { - GTEST_LOG_(INFO) << "SUB_Service_ExtConnectFailed_0100 RESTORE"; - ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - servicePtr_->ExtConnectFailed(BUNDLE_NAME, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SUB_Service_ExtConnectFailed_0100 BACKUP"; - ret = Init(IServiceReverse::Scenario::BACKUP); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - servicePtr_->ExtConnectFailed(BUNDLE_NAME, BError(BError::Codes::OK)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtConnectFailed."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtConnectFailed_0100"; -} - -/** - * @tc.number: SUB_Service_ExtConnectDone_0100 - * @tc.name: SUB_Service_ExtConnectDone_0100 - * @tc.desc: 测试 ExtConnectDone 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_ExtConnectDone_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ExtConnectDone_0100"; - try { - servicePtr_->ExtConnectDone(BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtConnectDone."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtConnectDone_0100"; -} - -/** - * @tc.number: SUB_Service_StopAll_0100 - * @tc.name: SUB_Service_StopAll_0100 - * @tc.desc: 测试 StopAll 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_StopAll_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_StopAll_0100"; - try { - servicePtr_->StopAll(nullptr, true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by StopAll."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_StopAll_0100"; -} - -/** - * @tc.number: SUB_Service_OnStop_0100 - * @tc.name: SUB_Service_OnStop_0100 - * @tc.desc: 测试 OnStop 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ServiceTest, SUB_Service_OnStop_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnStop_0100"; - try { - servicePtr_->OnStop(); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by OnStop."; - } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnStop_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp deleted file mode 100644 index b2cb332e8..000000000 --- a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "element_name.h" -#include "ext_extension_mock.h" -#include "module_ipc/svc_backup_connection.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -constexpr int32_t WAIT_TIME = 1; -} // namespace - -class SvcBackupConnectionTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override; - void TearDown() override; - sptr backupCon_ = nullptr; -}; - -static void CallDied(const std::string &&name) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-CallDied SUCCESS"; -} - -static void CallDone(const std::string &&name) -{ - GTEST_LOG_(INFO) << "ServiceReverseProxyTest-CallDone SUCCESS"; -} - -void SvcBackupConnectionTest::SetUp() -{ - backupCon_ = sptr(new SvcBackupConnection(CallDied, CallDone)); -} -void SvcBackupConnectionTest::TearDown() -{ - backupCon_ = nullptr; -} - -/** - * @tc.number: SUB_BackupConnection_OnAbilityConnectDone_0100 - * @tc.name: SUB_BackupConnection_OnAbilityConnectDone_0100 - * @tc.desc: 测试 OnAbilityConnectDone 链接回调接口调用成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcBackupConnectionTest, SUB_BackupConnection_OnAbilityConnectDone_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-begin SUB_BackupConnection_OnAbilityConnectDone_0100"; - AppExecFwk::ElementName element; - string bundleName = ""; - element.SetBundleName(bundleName); - int resultCode = 1; - sptr mock = sptr(new BackupExtExtensionMock()); - backupCon_->OnAbilityConnectDone(element, mock->AsObject(), resultCode); - bool ret = backupCon_->IsExtAbilityConnected(); - EXPECT_TRUE(ret); - mock = nullptr; - backupCon_->OnAbilityConnectDone(element, nullptr, resultCode); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-end SUB_BackupConnection_OnAbilityConnectDone_0100"; -} - -/** - * @tc.number: SUB_BackupConnection_OnAbilityDisconnectDone_0100 - * @tc.name: SUB_BackupConnection_OnAbilityDisconnectDone_0100 - * @tc.desc: 测试 OnAbilityDisconnectDone 链接回调接口调用成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcBackupConnectionTest, SUB_BackupConnection_OnAbilityDisconnectDone_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-begin SUB_BackupConnection_OnAbilityDisconnectDone_0100"; - AppExecFwk::ElementName element; - string bundleName = ""; - element.SetBundleName(bundleName); - int resultCode = 1; - backupCon_->OnAbilityDisconnectDone(element, resultCode); - bool ret = backupCon_->IsExtAbilityConnected(); - EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-end SUB_BackupConnection_OnAbilityDisconnectDone_0100"; -} - -/** - * @tc.number: SUB_BackupConnection_GetBackupExtProxy_0100 - * @tc.name: SUB_BackupConnection_GetBackupExtProxy_0100 - * @tc.desc: 测试 GetBackupExtProxy 获取连接状态接口调用成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcBackupConnectionTest, SUB_BackupConnection_GetBackupExtProxy_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-begin SUB_BackupConnection_GetBackupExtProxy_0100"; - auto proxy = backupCon_->GetBackupExtProxy(); - EXPECT_EQ(proxy, nullptr); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-end SUB_BackupConnection_GetBackupExtProxy_0100"; -} - -/** - * @tc.number: SUB_BackupConnection_ConnectBackupExtAbility_0100 - * @tc.name: SUB_BackupConnection_ConnectBackupExtAbility_0100 - * @tc.desc: 测试 ConnectBackupExtAbility 拉起extension接口调用成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcBackupConnectionTest, SUB_BackupConnection_ConnectBackupExtAbility_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-begin SUB_BackupConnection_ConnectBackupExtAbility_0100"; - AAFwk::Want want; - ErrCode ret = backupCon_->ConnectBackupExtAbility(want); - EXPECT_NE(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-end SUB_BackupConnection_ConnectBackupExtAbility_0100"; -} - -static void CallBack(sptr backupCon) -{ - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-CallBack Begin"; - sleep(WAIT_TIME); - backupCon->OnAbilityDisconnectDone({}, WAIT_TIME); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-CallBack End"; -} - -/** - * @tc.number: SUB_BackupConnection_DisconnectBackupExtAbility_0100 - * @tc.name: SUB_BackupConnection_DisconnectBackupExtAbility_0100 - * @tc.desc: 测试 DisconnectBackupExtAbility 拉起extension接口调用成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcBackupConnectionTest, SUB_BackupConnection_DisconnectBackupExtAbility_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-begin SUB_BackupConnection_DisconnectBackupExtAbility_0100"; - ErrCode ret = backupCon_->DisconnectBackupExtAbility(); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-DisconnectBackupExtAbility async Begin"; - auto future = std::async(std::launch::async, CallBack, backupCon_); - sleep(WAIT_TIME); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-DisconnectBackupExtAbility Branches Begin"; - ret = backupCon_->DisconnectBackupExtAbility(); - EXPECT_EQ(ret, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-DisconnectBackupExtAbility Branches End"; - future.get(); - GTEST_LOG_(INFO) << "SvcBackupConnectionTest-end SUB_BackupConnection_DisconnectBackupExtAbility_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp deleted file mode 100644 index 708699d79..000000000 --- a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "b_error/b_error.h" -#include "ext_extension_mock.h" -#include "module_ipc/svc_extension_proxy.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -class SvcExtensionProxyTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() override; - void TearDown() override; - sptr proxy_ = nullptr; - sptr mock_ = nullptr; -}; - -void SvcExtensionProxyTest::SetUp() -{ - mock_ = sptr(new BackupExtExtensionMock()); - proxy_ = sptr(new SvcExtensionProxy(mock_)); -} -void SvcExtensionProxyTest::TearDown() -{ - mock_ = nullptr; - proxy_ = nullptr; -} - -/** - * @tc.number: SUB_Ext_Extension_proxy_GetFileHandle_0100 - * @tc.name: SUB_Ext_Extension_proxy_GetFileHandle_0100 - * @tc.desc: 测试 GetFileHandle 获取真实文件接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_GetFileHandle_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_GetFileHandle_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &BackupExtExtensionMock::InvokeGetFileHandleRequest)) - .WillOnce(Return(EPERM)); - string fileName = "1.tar"; - UniqueFd fd = proxy_->GetFileHandle(fileName); - EXPECT_GT(fd, BError(BError::Codes::OK)); - - UniqueFd fdErr = proxy_->GetFileHandle(fileName); - EXPECT_LT(fdErr, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_GetFileHandle_0100"; -} - -/** - * @tc.number: SUB_Ext_Extension_proxy_HandleClear_0100 - * @tc.name: SUB_Ext_Extension_proxy_HandleClear_0100 - * @tc.desc: 测试 HandleClear 接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleClear_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleClear_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &BackupExtExtensionMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - ErrCode ret = proxy_->HandleClear(); - EXPECT_EQ(BError(BError::Codes::OK), ret); - - ret = proxy_->HandleClear(); - EXPECT_NE(BError(BError::Codes::OK), ret); - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_HandleClear_0100"; -} - -/** - * @tc.number: SUB_Ext_Extension_proxy_HandleBackup_0100 - * @tc.name: SUB_Ext_Extension_proxy_HandleBackup_0100 - * @tc.desc: 测试 HandleBackup 接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleBackup_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleBackup_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &BackupExtExtensionMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - ErrCode ret = proxy_->HandleBackup(); - EXPECT_EQ(BError(BError::Codes::OK), ret); - - ret = proxy_->HandleBackup(); - EXPECT_NE(BError(BError::Codes::OK), ret); - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_HandleBackup_0100"; -} - -/** - * @tc.number: SUB_Ext_Extension_proxy_PublishFile_0100 - * @tc.name: SUB_Ext_Extension_proxy_PublishFile_0100 - * @tc.desc: 测试 PublishFile 接口调用成功和失败 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_PublishFile_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_PublishFile_0100"; - EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) - .WillOnce(Invoke(mock_.GetRefPtr(), &BackupExtExtensionMock::InvokeSendRequest)) - .WillOnce(Return(EPERM)); - string fileName = "1.tar"; - ErrCode ret = proxy_->PublishFile(fileName); - EXPECT_EQ(BError(BError::Codes::OK), ret); - - ret = proxy_->PublishFile(fileName); - EXPECT_NE(BError(BError::Codes::OK), ret); - GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_PublishFile_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp deleted file mode 100644 index de055dc42..000000000 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_json/b_json_entity_ext_manage.h" -#include "ext_extension_mock.h" -#include "file_ex.h" -#include "module_ipc/service.h" -#include "module_ipc/svc_session_manager.h" -#include "service_reverse_mock.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace testing; -using namespace std; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup"; -const string MANAGE_JSON = "manage.json"; -const string FILE_NAME = "1.tar"; -constexpr int32_t SERVICE_ID = 5203; -constexpr int32_t CLIENT_TOKEN_ID = 100; -} // namespace - -class SvcSessionManagerTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp() override {}; - void TearDown() override {}; - void Init(IServiceReverse::Scenario scenario); - - static inline sptr sessionManagerPtr_ = nullptr; - static inline sptr remote_ = nullptr; - static inline sptr servicePtr_ = nullptr; -}; - -void SvcSessionManagerTest::SetUpTestCase(void) -{ - GTEST_LOG_(INFO) << "SetUpTestCase enter"; - remote_ = sptr(new ServiceReverseMock()); - servicePtr_ = sptr(new Service(SERVICE_ID)); - sessionManagerPtr_ = sptr(new SvcSessionManager(wptr(servicePtr_))); -} - -void SvcSessionManagerTest::TearDownTestCase(void) -{ - GTEST_LOG_(INFO) << "TearDownTestCase enter"; - sessionManagerPtr_ = nullptr; - servicePtr_ = nullptr; - remote_ = nullptr; -} - -void SvcSessionManagerTest::Init(IServiceReverse::Scenario scenario) -{ - vector bundleNames; - map backupExtNameMap; - bundleNames.emplace_back(BUNDLE_NAME); - auto setBackupExtNameMap = [](const string &bundleName) { - BackupExtInfo info {}; - info.backupExtName = BUNDLE_NAME; - info.receExtManageJson = false; - info.receExtAppDone = false; - return make_pair(bundleName, info); - }; - transform(bundleNames.begin(), bundleNames.end(), inserter(backupExtNameMap, backupExtNameMap.end()), - setBackupExtNameMap); - sessionManagerPtr_->Active({.clientToken = CLIENT_TOKEN_ID, - .scenario = scenario, - .backupExtNameMap = move(backupExtNameMap), - .clientProxy = remote_}); -} - -/** - * @tc.number: SUB_backup_sa_session_VerifyCallerAndScenario_0100 - * @tc.name: SUB_backup_sa_session_VerifyCallerAndScenario_0100 - * @tc.desc: 测试 VerifyCallerAndScenario 是否是有效的 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_VerifyCallerAndScenario_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_VerifyCallerAndScenario_0100"; - try { - Init(IServiceReverse::Scenario::RESTORE); - sessionManagerPtr_->VerifyCallerAndScenario(CLIENT_TOKEN_ID, IServiceReverse::Scenario::RESTORE); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by VerifyCallerAndScenario."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_VerifyCallerAndScenario_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_VerifyBundleName_0100 - * @tc.name: SUB_backup_sa_session_VerifyBundleName_0100 - * @tc.desc: 测试 VerifyBundleName 检验调用者给定的bundleName是否是有效的 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_VerifyBundleName_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_VerifyBundleName_0100"; - try { - string bundleName = BUNDLE_NAME; - sessionManagerPtr_->VerifyBundleName(bundleName); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by VerifyBundleName."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_VerifyBundleName_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_GetServiceReverseProxy_0100 - * @tc.name: SUB_backup_sa_session_GetServiceReverseProxy_0100 - * @tc.desc: 测试 GetServiceReverseProxy - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetServiceReverseProxy_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetServiceReverseProxy_0100"; - try { - auto proxy = sessionManagerPtr_->GetServiceReverseProxy(); - EXPECT_NE(proxy, nullptr); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetServiceReverseProxy."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetServiceReverseProxy_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_getscenario_0100 - * @tc.name: SUB_backup_sa_session_getscenario_0100 - * @tc.desc: 测试 GetScenario 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_getscenario_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_getscenario_0100"; - try { - IServiceReverse::Scenario scenario = sessionManagerPtr_->GetScenario(); - EXPECT_EQ(scenario, IServiceReverse::Scenario::RESTORE); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by getscenario."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_getscenario_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_onbunlefileready_0100 - * @tc.name: SUB_backup_sa_session_onbunlefileready_0100 - * @tc.desc: 测试 OnBunleFileReady 接口 restroe流程 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_onbunlefileready_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_onbunlefileready_0100"; - try { - bool condition = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME); - EXPECT_TRUE(condition); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by onbunlefileready."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_onbunlefileready_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_GetExtFileNameRequest_0100 - * @tc.name: SUB_backup_sa_session_GetExtFileNameRequest_0100 - * @tc.desc: 测试 GetExtFileNameRequest 获取暂存真实文件请求 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtFileNameRequest_0100"; - try { - sessionManagerPtr_->SetExtFileNameRequest(BUNDLE_NAME, FILE_NAME); - auto fileNameVec = sessionManagerPtr_->GetExtFileNameRequest(BUNDLE_NAME); - for (auto &fileName : fileNameVec) { - EXPECT_EQ(fileName, FILE_NAME); - } - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtFileNameRequest."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_GetExtConnection_0100 - * @tc.name: SUB_backup_sa_session_GetExtConnection_0100 - * @tc.desc: 测试 GetExtConnection 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtConnection_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtConnection_0100"; - try { - auto backupCon = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); - EXPECT_NE(backupCon, nullptr); - sptr mock = sptr(new BackupExtExtensionMock()); - backupCon->OnAbilityConnectDone({}, mock->AsObject(), 0); - backupCon->OnAbilityDisconnectDone({}, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtConnection."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtConnection_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_DumpInfo_0100 - * @tc.name: SUB_backup_sa_session_DumpInfo_0100 - * @tc.desc: 测试 DumpInfo 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_DumpInfo_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_DumpInfo_0100"; - try { - TestManager tm("SvcSessionManagerTest_GetFd_0100"); - string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - sessionManagerPtr_->DumpInfo(fd, {}); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by DumpInfo."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_DumpInfo_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_GetSchedBundleName_0100 - * @tc.name: SUB_backup_sa_session_GetSchedBundleName_0100 - * @tc.desc: 测试 GetSchedBundleName 调度器获取所需要的调度信息 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetSchedBundleName_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetSchedBundleName_0100"; - try { - string bundleName; - bool condition = sessionManagerPtr_->GetSchedBundleName(bundleName); - EXPECT_EQ(bundleName, BUNDLE_NAME); - EXPECT_TRUE(condition); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-GetSchedBundleName Branches"; - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::START); - condition = sessionManagerPtr_->GetSchedBundleName(bundleName); - EXPECT_FALSE(condition); - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::START); - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::START); - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::START); - condition = sessionManagerPtr_->GetSchedBundleName(bundleName); - EXPECT_FALSE(condition); - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::WAIT); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetSchedBundleName."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetSchedBundleName_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_GetServiceSchedAction_0100 - * @tc.name: SUB_backup_sa_session_GetServiceSchedAction_0100 - * @tc.desc: 测试 GetServiceSchedAction 获取状态 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetServiceSchedAction_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetServiceSchedAction_0100"; - try { - auto action = sessionManagerPtr_->GetServiceSchedAction(BUNDLE_NAME); - EXPECT_EQ(action, BConstants::ServiceSchedAction::WAIT); - - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::START); - action = sessionManagerPtr_->GetServiceSchedAction(BUNDLE_NAME); - EXPECT_EQ(action, BConstants::ServiceSchedAction::START); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-SetServiceSchedAction Branches"; - sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::FINISH); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetServiceSchedAction."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetServiceSchedAction_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_GetBackupExtName_0100 - * @tc.name: SUB_backup_sa_session_GetBackupExtName_0100 - * @tc.desc: 测试 GetBackupExtName 接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetBackupExtName_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetBackupExtName_0100"; - try { - string extName = sessionManagerPtr_->GetBackupExtName(BUNDLE_NAME); - EXPECT_EQ(extName, BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetBackupExtName."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetBackupExtName_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_removeextinfo_0100 - * @tc.name: SUB_backup_sa_session_removeextinfo_0100 - * @tc.desc: 测试 RemoveExtInfo 移除bundleName是否是有效的 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_removeextinfo_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_removeextinfo_0100"; - try { - sessionManagerPtr_->RemoveExtInfo(BUNDLE_NAME); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-RemoveExtInfo Branches"; - sessionManagerPtr_->RemoveExtInfo(BUNDLE_NAME); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by RemoveExtInfo."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_removeextinfo_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_Deactive_0100 - * @tc.name: SUB_backup_sa_session_Deactive_0100 - * @tc.desc: 测试 Deactive - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_Deactive_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_Deactive_0100"; - try { - sessionManagerPtr_->Deactive(nullptr, true); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-Deactive Branches One"; - sessionManagerPtr_->Deactive(nullptr, true); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-Deactive Branches Two"; - Init(IServiceReverse::Scenario::BACKUP); - sessionManagerPtr_->Deactive(remote_, false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-Deactive Branches Three"; - Init(IServiceReverse::Scenario::BACKUP); - sessionManagerPtr_->Deactive(remote_, true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by Deactive."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_Deactive_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_OnBunleExtManageInfo_0100 - * @tc.name: SUB_backup_sa_session_OnBunleExtManageInfo_0100 - * @tc.desc: 测试 OnBunleExtManageInfo - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_OnBunleExtManageInfo_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_OnBunleExtManageInfo_0100"; - try { - Init(IServiceReverse::Scenario::BACKUP); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-OnBunleFileReady Branches"; - auto ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, FILE_NAME); - EXPECT_FALSE(ret); - ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, FILE_NAME); - EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-OnBunleFileReady Branches End"; - TestManager tm("SvcSessionManagerTest_GetFd_0100"); - string filePath = tm.GetRootDirCurTest().append(MANAGE_JSON); - SaveStringToFile(filePath, R"({"fileName" : "1.tar"})"); - UniqueFd fd(open(filePath.data(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)); - sessionManagerPtr_->OnBunleExtManageInfo(BUNDLE_NAME, move(fd)); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-OnBunleFileReady Branches"; - ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, FILE_NAME); - EXPECT_FALSE(ret); - ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME); - EXPECT_FALSE(ret); - ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, MANAGE_JSON); - EXPECT_FALSE(ret); - ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, FILE_NAME); - EXPECT_TRUE(ret); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-OnBunleFileReady Branches End"; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by OnBunleExtManageInfo."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_OnBunleExtManageInfo_0100"; -} - -/** - * @tc.number: SUB_backup_sa_session_OnBunleFileReady_0200 - * @tc.name: SUB_backup_sa_session_OnBunleFileReady_0200 - * @tc.desc: 测试 OnBunleFileReady - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_OnBunleFileReady_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_OnBunleFileReady_0200"; - try { - sessionManagerPtr_->Deactive(nullptr, true); - Init(IServiceReverse::Scenario::BACKUP); - auto ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, MANAGE_JSON); - EXPECT_FALSE(ret); - ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, FILE_NAME); - EXPECT_FALSE(ret); - ret = sessionManagerPtr_->OnBunleFileReady(BUNDLE_NAME, FILE_NAME); - EXPECT_FALSE(ret); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by OnBunleFileReady."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_OnBunleFileReady_0200"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/BUILD.gn b/tests/unittests/backup_tools/BUILD.gn deleted file mode 100644 index 52a5bdfa7..000000000 --- a/tests/unittests/backup_tools/BUILD.gn +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_unittest("backup_tool_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup_mock}/b_filesystem/b_file_mock.cpp", - "${path_backup}/tests/mock/backup_kit_inner/b_session_backup_mock.cpp", - "${path_backup}/tools/backup_tool/src/tools_op.cpp", - "${path_backup}/tools/backup_tool/src/tools_op_backup.cpp", - "${path_backup}/tools/backup_tool/src/tools_op_check_sa.cpp", - "backup_tool/tools_op_backup_test.cpp", - "backup_tool/tools_op_check_sa_test.cpp", - "backup_tool/tools_op_test.cpp", - ] - sources += backup_mock_proxy_src - - include_dirs = [ - "${path_base}/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner", - "${path_backup}/tools/backup_tool/include", - ] - include_dirs += backup_mock_utils_include - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - ] - - external_deps = [ - "c_utils:utils", - "hitrace_native:hitrace_meter", - "ipc:ipc_core", - "samgr:samgr_proxy", - ] - use_exceptions = true -} - -ohos_unittest("backup_tool_restore_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup_mock}/b_filesystem/b_file_mock.cpp", - "${path_backup}/tests/mock/backup_kit_inner/b_session_restore_mock.cpp", - "${path_backup}/tools/backup_tool/src/tools_op.cpp", - "${path_backup}/tools/backup_tool/src/tools_op_restore.cpp", - "backup_tool/tools_op_restore_test.cpp", - ] - sources += backup_mock_proxy_src - - include_dirs = [ - "${path_base}/include", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner", - "${path_backup}/tools/backup_tool/include", - ] - include_dirs += backup_mock_utils_include - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils:backup_utils", - ] - - external_deps = [ - "c_utils:utils", - "hitrace_native:hitrace_meter", - "ipc:ipc_core", - "samgr:samgr_proxy", - ] - use_exceptions = true -} - -group("backup_test") { - testonly = true - - deps = [ - ":backup_tool_restore_test", - ":backup_tool_test", - ] -} diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp deleted file mode 100644 index b0cf9d9f0..000000000 --- a/tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include - -#include "tools_op.h" -#include "utils_mock_global_variable.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -class ToolsOpBackupTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_tools_op_backup_0100 - * @tc.name: SUB_backup_tools_op_backup_0100 - * @tc.desc: 测试backup流程 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpBackupTest, SUB_backup_tools_op_backup_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpBackupTest-begin SUB_backup_tools_op_backup_0100"; - try { - SetMockGetInstance(true); - GTEST_LOG_(INFO) << "ToolsOpBackupTest-info"; - map> mapArgToVal; - vector path = {"/data/backup/tmp"}; - mapArgToVal.insert(make_pair("pathCapFile", path)); - vector bundles = {"com.example.app2backup"}; - mapArgToVal.insert(make_pair("bundles", bundles)); - vector local = {"true"}; - mapArgToVal.insert(make_pair("isLocal", local)); - - // 创建测试路径 - string strPath = "/data/backup"; - mkdir(strPath.data(), S_IRWXU); - - // 尝试匹配当前命令,成功后执行 - GTEST_LOG_(INFO) << "ToolsOpBackupTest-backup"; - vector curOp; - curOp.emplace_back("backup"); - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - if (matchedOp != opeartions.end()) { - auto ret = matchedOp->Execute(mapArgToVal); - EXPECT_EQ(ret, 0); - } - - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - if (matchedOp != opeartions.end()) { - auto ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - SetMockGetInstance(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpBackupTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpBackupTest-end SUB_backup_tools_op_backup_0100"; -} - -/** - * @tc.number: SUB_backup_tools_op_backup_0200 - * @tc.name: SUB_backup_tools_op_backup_0200 - * @tc.desc: 测试Exec分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpBackupTest, SUB_backup_tools_op_backup_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpBackupTest-begin SUB_backup_tools_op_backup_0200"; - try { - GTEST_LOG_(INFO) << "ToolsOpBackupTest-The pathCapFile field is not contained."; - map> mapArgToVal; - vector bundles = {"com.example.app2backup"}; - vector path = {"/data/backup/tmp"}; - vector local = {"true"}; - mapArgToVal.insert(make_pair("bundles", bundles)); - mapArgToVal.insert(make_pair("isLocal", local)); - - vector curOp; - curOp.emplace_back("backup"); - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - int ret = 0; - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - - GTEST_LOG_(INFO) << "ToolsOpBackupTest-The bundles field is noGt contained."; - mapArgToVal.clear(); - mapArgToVal.insert(make_pair("pathCapFile", path)); - mapArgToVal.insert(make_pair("isLocal", local)); - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - - GTEST_LOG_(INFO) << "ToolsOpBackupTest-The isLocal field is noGt contained."; - mapArgToVal.clear(); - mapArgToVal.insert(make_pair("pathCapFile", path)); - mapArgToVal.insert(make_pair("bundles", bundles)); - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - - mapArgToVal.clear(); - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpBackupTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpBackupTest-end SUB_backup_tools_op_backup_0200"; -} - -/** - * @tc.number: SUB_backup_tools_op_backup_0300 - * @tc.name: SUB_backup_tools_op_backup_0300 - * @tc.desc: 测试Exec分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpBackupTest, SUB_backup_tools_op_backup_0300, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpBackupTest-begin SUB_backup_tools_op_backup_0300"; - try { - GTEST_LOG_(INFO) << "ToolsOpBackupTest-info"; - map> mapArgToVal; - vector path = {"/data/backup/tmp"}; - mapArgToVal.insert(make_pair("pathCapFile", path)); - vector bundles = {"com.example.app2backup"}; - mapArgToVal.insert(make_pair("bundles", bundles)); - vector local = {"false"}; - mapArgToVal.insert(make_pair("isLocal", local)); - - // 尝试匹配当前命令,成功后执行 - GTEST_LOG_(INFO) << "ToolsOpBackupTest-backup"; - vector curOp; - curOp.emplace_back("backup"); - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - if (matchedOp != opeartions.end()) { - auto ret = matchedOp->Execute(mapArgToVal); - EXPECT_EQ(ret, 0); - } - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpBackupTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpBackupTest-end SUB_backup_tools_op_backup_0300"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_check_sa_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_check_sa_test.cpp deleted file mode 100644 index 5e8fd4ced..000000000 --- a/tests/unittests/backup_tools/backup_tool/tools_op_check_sa_test.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include "tools_op.h" -#include "utils_mock_global_variable.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -class ToolsOpCheckSaTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_tools_op_check_sa_0100 - * @tc.name: SUB_backup_tools_op_check_sa_0100 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpCheckSaTest, SUB_backup_tools_op_check_sa_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpCheckSaTest-begin SUB_backup_tools_op_check_sa_0100"; - try { - GTEST_LOG_(INFO) << "ToolsOpCheckSaTest-info"; - map> mapArgToVal; - vector curOp; - curOp.emplace_back("check"); - curOp.emplace_back("sa"); - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - int ret = 0; - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_EQ(ret, 0); - } - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpCheckSaTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpCheckSaTest-end SUB_backup_tools_op_check_sa_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp deleted file mode 100644 index 97751fe3d..000000000 --- a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include - -#include "b_resources/b_constants.h" -#include "tools_op.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -namespace { -const string BUNDLE_NAME = "com.example.app2backup/"; -const string MANAGE_JSON = "manage.json"; -const string FILE_NAME = "1.tar"; -} // namespace - -class ToolsOpRestoreTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_tools_op_restore_0100 - * @tc.name: SUB_backup_tools_op_restore_0100 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpRestoreTest, SUB_backup_tools_op_restore_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin SUB_backup_tools_op_restore_0100"; - try { - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-info"; - map> mapArgToVal; - vector path = {"/data/backup/tmp"}; - mapArgToVal.insert(make_pair("pathCapFile", path)); - vector bundles = {"com.example.app2backup"}; - mapArgToVal.insert(make_pair("bundles", bundles)); - - // 创建测试路径以及测试环境 - string cmdMkdir = string("mkdir -p ") + BConstants::BACKUP_TOOL_RECEIVE_DIR.data() + BUNDLE_NAME; - system(cmdMkdir.c_str()); - string touchTar = string("touch ") + BConstants::BACKUP_TOOL_RECEIVE_DIR.data() + BUNDLE_NAME + FILE_NAME; - system(touchTar.c_str()); - string touchManage = string("touch ") + BConstants::BACKUP_TOOL_RECEIVE_DIR.data() + BUNDLE_NAME + MANAGE_JSON; - system(touchManage.c_str()); - - // 尝试匹配当前命令,成功后执行 - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-restore"; - vector curOp; - curOp.emplace_back("restore"); - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - if (matchedOp != opeartions.end()) { - auto ret = matchedOp->Execute(mapArgToVal); - EXPECT_EQ(ret, 0); - } - - GTEST_LOG_(INFO) << "GetLocalCapabilities is false"; - mapArgToVal.clear(); - mapArgToVal.insert(make_pair("pathCapFile", path)); - vector bundleVec = {"test"}; - mapArgToVal.insert(make_pair("bundles", bundleVec)); - if (matchedOp != opeartions.end()) { - auto ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end SUB_backup_tools_op_restore_0100"; -} - -/** - * @tc.number: SUB_backup_tools_op_restore_0200 - * @tc.name: SUB_backup_tools_op_restore_0200 - * @tc.desc: 测试 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpRestoreTest, SUB_backup_tools_op_restore_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin SUB_backup_tools_op_restore_0200"; - try { - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-The pathCapFile field is not contained."; - map> mapArgToVal; - vector bundles = {"com.example.app2backup"}; - vector path = {"/data/backup/tmp"}; - mapArgToVal.insert(make_pair("bundles", bundles)); - - vector curOp; - curOp.emplace_back("restore"); - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - int ret = 0; - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-The bundles field is not contained."; - mapArgToVal.clear(); - mapArgToVal.insert(make_pair("pathCapFile", path)); - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - - mapArgToVal.clear(); - if (matchedOp != opeartions.end()) { - ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end SUB_backup_tools_op_restore_0200"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_test.cpp deleted file mode 100644 index 526295b50..000000000 --- a/tests/unittests/backup_tools/backup_tool/tools_op_test.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include - -#include "tools_op.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -class ToolsOpTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_tools_op_0100 - * @tc.name: SUB_backup_tools_op_0100 - * @tc.desc: 测试Execute分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpTest, SUB_backup_tools_op_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpTest-begin SUB_backup_tools_op_0100"; - try { - GTEST_LOG_(INFO) << "ToolsOpTest-info"; - bool autoTest = ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { - .opName = {"test"}, - .funcGenHelpMsg = nullptr, - .funcExec = nullptr, - }}); - EXPECT_TRUE(autoTest); - map> mapArgToVal; - vector curOp; - curOp.emplace_back("test"); - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - if (matchedOp != opeartions.end()) { - matchedOp->Execute(mapArgToVal); - } - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpTest-end SUB_backup_tools_op_0100"; -} - -/** - * @tc.number: SUB_backup_tools_op_0200 - * @tc.name: SUB_backup_tools_op_0200 - * @tc.desc: 测试Register分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(ToolsOpTest, SUB_backup_tools_op_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ToolsOpTest-begin SUB_backup_tools_op_0200"; - try { - GTEST_LOG_(INFO) << "ToolsOpTest-info"; - bool autoTest = ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { - .opName = {"???"}, - .funcGenHelpMsg = nullptr, - .funcExec = nullptr, - }}); - EXPECT_FALSE(autoTest); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ToolsOpTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ToolsOpTest-end SUB_backup_tools_op_0200"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/BUILD.gn b/tests/unittests/backup_utils/BUILD.gn deleted file mode 100644 index 9da04ca4c..000000000 --- a/tests/unittests/backup_utils/BUILD.gn +++ /dev/null @@ -1,136 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_unittest("b_error_test") { - module_out_path = path_module_out_tests - - sources = [ "b_error/b_error_test.cpp" ] - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils/:backup_utils", - ] - - use_exceptions = true -} - -ohos_unittest("b_file_test") { - module_out_path = path_module_out_tests - - sources = [ - "b_filesystem/b_dir_test.cpp", - "b_filesystem/b_file_test.cpp", - ] - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils/:backup_utils", - ] - - use_exceptions = true -} - -ohos_unittest("b_json_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup}/utils/src/b_json/b_json_entity_extension_config.cpp", - "b_json/b_json_cached_entity_test.cpp", - "b_json/b_json_entity_ext_manage_test.cpp", - "b_json/b_json_entity_extension_config_test.cpp", - ] - sources += backup_mock_parameter_src - - include_dirs = [ "${path_base}/include" ] - include_dirs += backup_mock_parameter_include_dirs - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils/:backup_utils", - "${path_googletest}:gmock_main", - ] - - use_exceptions = true -} - -ohos_unittest("b_tarball_cmdline_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup_mock}/b_process/b_process_mock.cpp", - "b_tarball/b_tarball_cmdline_test.cpp", - ] - - include_dirs = [ - "${path_base}/include", - "${path_backup}/utils/include", - ] - - deps = [ "${path_backup}/tests/utils:backup_test_utils" ] - external_deps = [ "c_utils:utils" ] - - use_exceptions = true -} - -ohos_unittest("b_tarball_factory_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup_mock}/b_tarball/b_tarball_cmdline_mock.cpp", - "b_tarball/b_tarball_factory_test.cpp", - ] - - include_dirs = [ - "${path_base}/include", - "${path_backup}/utils/include", - ] - - deps = [ "${path_backup}/tests/utils:backup_test_utils" ] - external_deps = [ "c_utils:utils" ] - use_exceptions = true -} - -ohos_unittest("b_process_test") { - module_out_path = path_module_out_tests - - sources = [ "b_process/b_process_test.cpp" ] - - include_dirs = [ - "${path_base}/include", - "${path_backup}/utils/include", - ] - - deps = [ - "${path_backup}/tests/utils:backup_test_utils", - "${path_backup}/utils/:backup_utils", - ] - external_deps = [ "c_utils:utils" ] - - use_exceptions = true -} - -group("backup_test") { - testonly = true - - deps = [ - ":b_error_test", - ":b_file_test", - ":b_json_test", - ":b_process_test", - ":b_tarball_cmdline_test", - ":b_tarball_factory_test", - ] -} diff --git a/tests/unittests/backup_utils/b_error/b_error_test.cpp b/tests/unittests/backup_utils/b_error/b_error_test.cpp deleted file mode 100644 index be2638eae..000000000 --- a/tests/unittests/backup_utils/b_error/b_error_test.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "b_error/b_error.h" - -namespace OHOS::FileManagement::Backup { -class BErrorTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_b_error_construction_0100 - * @tc.name: b_error_construction_0100 - * @tc.desc: Test function of construction interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_construction_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_construction_0100"; - try { - BError be(BError::Codes::OK); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BErrorTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BErrorTest-end b_error_construction_0100"; -} - -/** - * @tc.number: SUB_backup_b_error_construction_0300 - * @tc.name: b_error_construction_0300 - * @tc.desc: Test function of construction interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_construction_0300, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_construction_0300"; - try { - std::string_view extraMsg; - BError be(BError::Codes::OK, extraMsg); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BErrorTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BErrorTest-end b_error_construction_0300"; -} - -/** - * @tc.number: SUB_backup_b_error_construction_0500 - * @tc.name: b_error_construction_0500 - * @tc.desc: Test function of construction interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_construction_0500, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_construction_0500"; - try { - throw BError(BError::Codes::UTILS_INVAL_JSON_ENTITY); - EXPECT_TRUE(false); - } catch (const BError &e) { - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BErrorTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BErrorTest-end b_error_construction_0500"; -} - -/** - * @tc.number: SUB_backup_b_error_GetCode_0100 - * @tc.name: b_error_GetCode_0100 - * @tc.desc: Test function of GetCode interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_GetCode_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCode_0100"; - BError be(BError::Codes::OK); - int result = be.GetCode(); - EXPECT_EQ(result, 0); - GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCode_0100"; -} - -/** - * @tc.number: SUB_backup_b_error_GetRawCode_0100 - * @tc.name: b_error_GetRawCode_0100 - * @tc.desc: Test function of GetRawCode interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_GetRawCode_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetRawCode_0100"; - BError be(BError::Codes::OK); - BError::Codes result = be.GetRawCode(); - EXPECT_EQ(result, BError::Codes::OK); - GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetRawCode_0100"; -} - -/** - * @tc.number: SUB_backup_b_error_what_0100 - * @tc.name: b_error_what_0100 - * @tc.desc: Test function of what interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_what_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_what_0100"; - BError be(BError::Codes::OK); - auto result = be.what(); - EXPECT_NE(result, nullptr); - GTEST_LOG_(INFO) << "BErrorTest-end b_error_what_0100"; -} - -/** - * @tc.number: SUB_backup_b_error_bool_0100 - * @tc.name: b_error_bool_0100 - * @tc.desc: Test function of bool interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_bool_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_bool_0100"; - bool result = BError(); - EXPECT_FALSE(result); - GTEST_LOG_(INFO) << "BErrorTest-end b_error_bool_0100"; -} - -/** - * @tc.number: SUB_backup_b_error_int_0100 - * @tc.name: b_error_int_0100 - * @tc.desc: Test function of int interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BErrorTest, b_error_int_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BErrorTest-begin b_error_int_0100"; - int result = BError(); - EXPECT_EQ(result, 0); - GTEST_LOG_(INFO) << "BErrorTest-end b_error_int_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp b/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp deleted file mode 100644 index e0c78540b..000000000 --- a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include -#include - -#include -#include -#include - -#include "b_filesystem/b_dir.h" -#include "b_process/b_process.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class BDirTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_b_dir_GetDirFiles_0100 - * @tc.name: b_dir_GetDirFiles_0100 - * @tc.desc: Test function of GetDirFiles interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BDirTest, b_dir_GetDirFiles_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BDirTest-begin b_dir_GetDirFiles_0100"; - try { - TestManager tm("b_dir_GetDirFiles_0100"); - - string preparedDir = tm.GetRootDirCurTest(); - string touchFilePrefix = string("touch ") + preparedDir; - system(touchFilePrefix.append("a.txt").c_str()); - system(touchFilePrefix.append("b.txt").c_str()); - system(touchFilePrefix.append("c.txt").c_str()); - - bool bSucc; - vector out; - tie(bSucc, out) = BDir::GetDirFiles(preparedDir); - - vector expectedRes = {preparedDir.append("a.txt"), preparedDir.append("b.txt"), - preparedDir.append("c.txt")}; - EXPECT_EQ(out, expectedRes); - - tie(bSucc, out) = BDir::GetDirFiles("dev"); - EXPECT_EQ(bSucc, true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetDirFiles_0100"; -} - -/** - * @tc.number: SUB_backup_b_dir_GetBigFiles_0100 - * @tc.name: b_dir_GetBigFiles_0100 - * @tc.desc: 测试GetBigFiles接口是否能成功获取大文件 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BDirTest, b_dir_GetBigFiles_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BDirTest-begin b_dir_GetBigFiles_0100"; - try { - TestManager tm("b_dir_GetBigFiles_0100"); - string rootDir = tm.GetRootDirCurTest(); - string filePath1 = rootDir + "a.txt"; - string filePath2 = rootDir + "b.txt"; - // 文件大小大于等于1GB(1024MB)的文件属于大文件,因此这里创建大小为1025MB和1026MB的大文件 - auto [bFatalErr, ret] = - BProcess::ExecuteCmd({"dd", "if=/dev/urandom", ("of=" + filePath1).c_str(), "bs=1M", "count=1025"}); - EXPECT_FALSE(bFatalErr); - EXPECT_EQ(ret, 0); - tie(bFatalErr, ret) = - BProcess::ExecuteCmd({"dd", "if=/dev/urandom", ("of=" + filePath2).c_str(), "bs=1M", "count=1026"}); - EXPECT_FALSE(bFatalErr); - EXPECT_EQ(ret, 0); - vector includes = {rootDir}; - vector excludes = {filePath2}; - auto [errCode, mpNameToStat] = BDir::GetBigFiles(includes, excludes); - EXPECT_EQ(errCode, ERR_OK); - EXPECT_EQ(mpNameToStat.at(filePath1).st_size, 1024 * 1024 * 1025); - EXPECT_EQ(mpNameToStat.find(filePath2), mpNameToStat.end()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetBigFiles_0100"; -} - -/** - * @tc.number: SUB_backup_b_dir_GetBigFiles_0200 - * @tc.name: b_dir_GetBigFiles_0200 - * @tc.desc: 测试GetBigFiles接口 分支逻辑 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BDirTest, b_dir_GetBigFiles_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BDirTest-begin b_dir_GetBigFiles_0200"; - try { - vector includes = {{}, {}}; - vector excludes = {{}}; - auto [errCode, mpNameToStat] = BDir::GetBigFiles(includes, excludes); - EXPECT_EQ(errCode, ERR_OK); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetBigFiles_0200"; -} - -/** - * @tc.number: SUB_backup_b_dir_GetBigFiles_0300 - * @tc.name: b_dir_GetBigFiles_0300 - * @tc.desc: 测试GetBigFiles接口 分支逻辑 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BDirTest, b_dir_GetBigFiles_0300, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BDirTest-begin b_dir_GetBigFiles_0300"; - try { - TestManager tm("b_dir_GetBigFiles_0300"); - string preparedDir = tm.GetRootDirCurTest(); - string cmdMkdir = string("mkdir -p ") + preparedDir + string("test/test1/test2"); - system(cmdMkdir.c_str()); - string touchFilePrefix = string("touch ") + preparedDir; - system(touchFilePrefix.append("a.txt").c_str()); - system(touchFilePrefix.append("b.txt").c_str()); - system(touchFilePrefix.append("c.txt").c_str()); - - touchFilePrefix = string("touch ") + preparedDir + string("test/"); - system(touchFilePrefix.append("a.txt").c_str()); - system(touchFilePrefix.append("b.txt").c_str()); - system(touchFilePrefix.append("c.txt").c_str()); - touchFilePrefix = string("touch ") + preparedDir + string("test/test1/test2"); - system(touchFilePrefix.append("a.txt").c_str()); - system(touchFilePrefix.append("b.txt").c_str()); - system(touchFilePrefix.append("c.txt").c_str()); - vector includes = {preparedDir + string("/*"), preparedDir + string("test")}; - vector excludes = {preparedDir + string("/test/test1/test2"), {}}; - auto [errCode, mpNameToStat] = BDir::GetBigFiles(includes, excludes); - EXPECT_EQ(errCode, ERR_OK); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetBigFiles_0300"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_filesystem/b_file_test.cpp b/tests/unittests/backup_utils/b_filesystem/b_file_test.cpp deleted file mode 100644 index 22b7c54bf..000000000 --- a/tests/unittests/backup_utils/b_filesystem/b_file_test.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include - -#include -#include - -#include "b_filesystem/b_file.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class BFileTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @brief 创建测试文件 - * - * @return tuple 创建结果、文件路径、文件内容 - */ -static tuple GetTestFile(const TestManager &tm) -{ - string path = tm.GetRootDirCurTest(); - string filePath = path + "temp.txt"; - string content = "backup test"; - if (bool contentCreate = SaveStringToFile(filePath, content, true); !contentCreate) { - throw system_error(errno, system_category()); - } - return {filePath, content}; -} - -/** - * @tc.number: SUB_backup_b_file_ReadFile_0100 - * @tc.name: b_file_ReadFile_0100 - * @tc.desc: Test function of ReadFile interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BFileTest, b_file_ReadFile_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BFileTest-begin b_file_ReadFile_0100"; - try { - TestManager tm(__func__); - const auto [filePath, content] = GetTestFile(tm); - BFile bf; - unique_ptr result = bf.ReadFile(UniqueFd(open(filePath.data(), O_RDWR))); - string readContent(result.get()); - EXPECT_EQ(readContent.compare(content), 0); - } catch (const exception &e) { - GTEST_LOG_(INFO) << "BFileTest-an exception occurred by ReadFile."; - e.what(); - } - GTEST_LOG_(INFO) << "BFileTest-end b_file_ReadFile_0100"; -} - -/** - * @tc.number: SUB_backup_b_file_SendFile_0100 - * @tc.name: b_file_SendFile_0100 - * @tc.desc: 测试SendFile接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BFileTest, b_file_SendFile_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BFileTest-begin b_file_SendFile_0100"; - try { - TestManager tm(__func__); - const auto [filePath, content] = GetTestFile(tm); - TestManager tmInFile("b_file_GetFd_0100"); - string fileInPath = tmInFile.GetRootDirCurTest().append("1.tar"); - BFile::SendFile(UniqueFd(open(filePath.data(), O_RDWR)), - UniqueFd(open(fileInPath.data(), O_RDWR | O_CREAT, S_IRWXU))); - } catch (const exception &e) { - GTEST_LOG_(INFO) << "BFileTest-an exception occurred by SendFile."; - e.what(); - } - GTEST_LOG_(INFO) << "BFileTest-end b_file_SendFile_0100"; -} - -/** - * @tc.number: SUB_backup_b_file_CopyFile_0100 - * @tc.name: b_file_CopyFile_0100 - * @tc.desc: 测试CopyFile接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BFileTest, b_file_CopyFile_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BFileTest-begin b_file_CopyFile_0100"; - try { - TestManager tm(__func__); - const auto [filePath, content] = GetTestFile(tm); - TestManager tmInFile("b_file_GetFd_0200"); - string fileInPath = tmInFile.GetRootDirCurTest().append("1.txt"); - auto ret = BFile::CopyFile(filePath, fileInPath); - EXPECT_TRUE(ret); - GTEST_LOG_(INFO) << "BFileTest-CopyFile Branches"; - ret = BFile::CopyFile(filePath, filePath); - EXPECT_TRUE(ret); - } catch (const exception &e) { - GTEST_LOG_(INFO) << "BFileTest-an exception occurred by CopyFile."; - e.what(); - } - GTEST_LOG_(INFO) << "BFileTest-end b_file_CopyFile_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp b/tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp deleted file mode 100644 index 5e8f89c8a..000000000 --- a/tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include - -#include "b_json/b_json_cached_entity.h" -#include "b_json/b_json_entity_caps.h" -#include "directory_ex.h" -#include "file_ex.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -class BJsonCachedEntityTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_backup_b_json_construction_0100 - * @tc.name: b_json_construction_0100 - * @tc.desc: Test function of construction interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonCachedEntityTest, b_json_construction_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-begin b_json_construction_0100"; - try { - TestManager tm("b_json_construction_0100"); - - std::string path = tm.GetRootDirCurTest(); - std::string filePath = path + ".json"; - BJsonCachedEntity jce(UniqueFd(open(filePath.data(), O_RDWR | O_CREAT, 0600))); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-end b_json_construction_0100"; -} - -/** - * @tc.number: SUB_backup_b_json_Structuralize_0100 - * @tc.name: b_json_Structuralize_0100 - * @tc.desc: Test function of Structuralize interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonCachedEntityTest, b_json_Structuralize_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-begin b_json_Structuralize_0100"; - try { - TestManager tm("b_json_Structuralize_0100"); - - std::string path = tm.GetRootDirCurTest(); - std::string filePath = path + ".json"; - BJsonCachedEntity jce(UniqueFd(open(filePath.data(), O_RDWR | O_CREAT, 0600))); - jce.Structuralize(); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-end b_json_Structuralize_0100"; -} - -/** - * @tc.number: SUB_backup_b_json_Persist_0100 - * @tc.name: b_json_Persist_0100 - * @tc.desc: Test function of Persist interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonCachedEntityTest, b_json_Persist_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-begin b_json_Persist_0100"; - try { - TestManager tm("b_json_Persist_0100"); - - std::string path = tm.GetRootDirCurTest(); - std::string filePath = path + ".json"; - BJsonCachedEntity jce(UniqueFd(open(filePath.data(), O_RDWR | O_CREAT, 0600))); - auto cache = jce.Structuralize(); - uint64_t space = 100; - cache.SetFreeDiskSpace(space); - jce.Persist(); - uint64_t result = cache.GetFreeDiskSpace(); - EXPECT_EQ(result, space); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-end b_json_Persist_0100"; -} - -/** - * @tc.number: SUB_backup_b_json_GetFd_0100 - * @tc.name: b_json_GetFd_0100 - * @tc.desc: Test function of GetFd interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonCachedEntityTest, b_json_GetFd_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-begin b_json_GetFd_0100"; - try { - TestManager tm("b_json_GetFd_0100"); - - std::string path = tm.GetRootDirCurTest(); - std::string filePath = path + ".json"; - BJsonCachedEntity jce(UniqueFd(open(filePath.data(), O_RDWR | O_CREAT, 0600))); - jce.GetFd(); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonCachedEntityTest-end b_json_GetFd_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp b/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp deleted file mode 100644 index 1720f689a..000000000 --- a/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp +++ /dev/null @@ -1,532 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - -#include "b_json/b_json_cached_entity.h" -#include "b_json/b_json_entity_ext_manage.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing::ext; - -class BJsonEntityExtManageTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -bool IsEqual(const struct stat &lf, const struct stat &rh) -{ - if (lf.st_size != rh.st_size) { - return false; - } - if (lf.st_atim.tv_sec != rh.st_atim.tv_sec) { - return false; - } - if (lf.st_atim.tv_nsec != rh.st_atim.tv_nsec) { - return false; - } - if (lf.st_mtim.tv_sec != rh.st_mtim.tv_sec) { - return false; - } - if (lf.st_mtim.tv_nsec != rh.st_mtim.tv_nsec) { - return false; - } - return true; -} - -bool IsEqual(const map> &lf, const map> &rh) -{ - if (lf.size() != rh.size()) { - return false; - } - - auto itemLF = lf.begin(); - auto itemRH = rh.begin(); - for (; itemLF != lf.end(); ++itemLF, ++itemRH) { - if (itemLF->first != itemRH->first) { - return false; - } - if (itemLF->second.first != itemRH->second.first) { - return false; - } - if (!IsEqual(itemLF->second.second, itemRH->second.second)) { - return false; - } - } - - return true; -} - -struct stat GetFileStat(const string &pathTestFile) -{ - struct stat sta = {}; - if (stat(pathTestFile.data(), &sta) == -1) { - GTEST_LOG_(INFO) << pathTestFile << " invoked stat failure, errno :" << errno; - throw BError(errno); - } - return sta; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0100 - * @tc.name: b_json_entity_ext_manage_0100 - * @tc.desc: 通过向接口SetExtManage传入不包含任何信息的空map参数,测试对索引文件的操作是否正确。 - * 0:通过向索引文件写入0条数据模拟对索引文件的(空)内容的测试覆盖 - * 1:调用接口SetExtManage,向索引文件写入数据 - * 2:调用接口GetExtManage,从索引文件读出文件名数据 - * 3:调用接口GetExtManageInfo,从索引文件读出文件详细数据(含文件名和对应文件的stat数据) - * 4:判断读出的文件名集合/文件详细数据记录个数是否为0 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0100"; - try { - // 预置文件数据 - // 索引文件pathManageFile - TestManager tm("b_json_entity_ext_manage_0100"); - string root = tm.GetRootDirCurTest(); - string pathManageFile = root + "manage.json"; - BJsonCachedEntity cachedEntity(UniqueFd(open(pathManageFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - - // 写入空数据 - map> info; - cache.SetExtManage(info); - - // 读取索引文件信息并做结果判断 - auto fileNames = cache.GetExtManage(); - EXPECT_EQ(fileNames.size(), 0ul); - auto fileInfo = cache.GetExtManageInfo(); - EXPECT_EQ(fileInfo.size(), 0ul); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0100"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0200 - * @tc.name: b_json_entity_ext_manage_0200 - * @tc.desc: 通过向接口SetExtManage传入包含一条信息的map参数,测试对索引文件的操作是否正确。 - * 0:通过向索引文件写入1条有效数据模拟对索引文件的(有)内容的测试覆盖 - * 1:调用接口SetExtManage,向索引文件写入数据 - * 2:调用接口GetExtManage,从索引文件读出文件名数据 - * 3:调用接口GetExtManageInfo,从索引文件读出文件详细数据(含文件名和对应文件的stat数据) - * 4:判断读出的文件名集合/文件详细数据记录个数是否和写入时相等 - * 5:判断读出的文件名集合/文件详细数据记录内容是否和写入时相等 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0200, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0200"; - try { - TestManager tm("b_json_entity_ext_manage_0200"); - - // 预置文件数据 - // 索引文件pathManageFile, 测试文件路径pathTestFile, 测试文件名testFileHexName - string root = tm.GetRootDirCurTest(); - string pathManageFile = root + "manage.json"; - string pathTestFile = root + "test.txt"; - string testFileHexName = "1234567890abcdef"; - SaveStringToFile(pathTestFile, "hello world"); - BJsonCachedEntity cachedEntity(UniqueFd(open(pathManageFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - - // 生成一条有用数据并写入索引文件 - map> info; - struct stat sta = {}; - info.emplace(testFileHexName, make_pair(pathTestFile, sta = GetFileStat(pathTestFile))); - cache.SetExtManage(info); - - // 读取索引文件内容并做结果判断 - auto fileNames = cache.GetExtManage(); - ASSERT_EQ(fileNames.size(), 1ul); - EXPECT_EQ(*fileNames.begin(), testFileHexName); - auto fileInfo = cache.GetExtManageInfo(); - ASSERT_EQ(fileInfo.size(), 1ul); - EXPECT_EQ(fileInfo.begin()->first, testFileHexName); - EXPECT_EQ(fileInfo.begin()->second.first, pathTestFile); - EXPECT_TRUE(IsEqual(fileInfo.begin()->second.second, sta)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0200"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0300 - * @tc.name: b_json_entity_ext_manage_0300 - * @tc.desc: 通过向接口SetExtManage传入包含三条信息的map参数,测试对索引文件的操作是否正确。 - * 0:通过向索引文件写入3条有效数据模拟对索引文件的(无穷)内容的测试覆盖 - * 1:调用接口SetExtManage,向索引文件写入数据 - * 2:调用接口GetExtManage,从索引文件读出文件名数据 - * 3:调用接口GetExtManageInfo,从索引文件读出文件详细数据(含文件名和对应文件的stat数据) - * 4:判断读出的文件名集合/文件详细数据记录个数是否和写入时相等 - * 5:判断读出的文件名集合/文件详细数据记录内容是否和写入时相等 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0300, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0300"; - try { - TestManager tm("b_json_entity_ext_manage_0300"); - - // 预置文件数据 - // 索引文件pathManageFile1/2/3, 测试文件路径pathTestFile1/2/3, 测试文件名testFile1/2/3HexName - string root = tm.GetRootDirCurTest(); - string pathManageFile = root + "manage.json"; - string pathTestFile1 = root + "test1.txt"; - string pathTestFile2 = root + "test2.txt"; - string pathTestFile3 = root + "test3.txt"; - string testFile1HexName = "1234567890abcde1"; - string testFile2HexName = "1234567890abcde2"; - string testFile3HexName = "1234567890abcde3"; - SaveStringToFile(pathTestFile1, "h"); - SaveStringToFile(pathTestFile2, "hello"); - SaveStringToFile(pathTestFile3, "hello world"); - BJsonCachedEntity cachedEntity(UniqueFd(open(pathManageFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - - // 生成三条有用数据并写入索引文件 - map> info; - info.emplace(testFile1HexName, make_pair(pathTestFile1, GetFileStat(pathTestFile1))); - info.emplace(testFile2HexName, make_pair(pathTestFile2, GetFileStat(pathTestFile2))); - info.emplace(testFile3HexName, make_pair(pathTestFile3, GetFileStat(pathTestFile3))); - cache.SetExtManage(info); - - // 预置结果集,用以在读取索引文件后做结果判断 - set resultFileName {testFile1HexName, testFile2HexName, testFile3HexName}; - - // 读取索引文件内容并做结果判断 - auto fileNames = cache.GetExtManage(); - EXPECT_EQ(fileNames.size(), info.size()); - EXPECT_EQ(fileNames, resultFileName); - auto fileInfo = cache.GetExtManageInfo(); - EXPECT_EQ(fileInfo.size(), info.size()); - EXPECT_TRUE(IsEqual(fileInfo, info)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0300"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0400 - * @tc.name: b_json_entity_ext_manage_0400 - * @tc.desc: 通过向接口SetExtManage传入包含三条信息的map参数,测试对索引文件的操作是否正确。 - * 0:通过向索引文件写入3条有效数据模拟覆盖对索引文件的(无穷)内容的测试覆盖 - * 0:通过向索引文件的记录一写入0条、记录二写入1条、记录三写入2条有效硬链接数据模拟对索引文件含 - * 有硬链接(空、有、无穷)个的测试覆盖 - * 0:通过调用接口SetHardLinkInfo向索引文件中对应记录添加硬链接 - * 1:调用接口SetExtManage,向索引文件写入数据 - * 2:调用接口GetExtManage,从索引文件读出文件名数据 - * 3:调用接口GetExtManageInfo,从索引文件读出文件详细数据(含文件名和对应文件的stat数据) - * 4:判断读出的文件名集合/文件详细数据记录个数是否和写入时相等 - * 5:判断读出的文件名集合/文件详细数据记录内容是否和写入时相等 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0400, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0400"; - try { - TestManager tm("b_json_entity_ext_manage_0400"); - - // 预置文件数据 - // 索引文件pathManageFile1/2/3, 测试文件路径pathTestFile1/2/3, 测试文件名testFile1/2/3HexName - string root = tm.GetRootDirCurTest(); - string pathManageFile = root + "manage.json"; - string pathTestFile1 = root + "test1.txt"; - string pathTestFile2 = root + "test2.txt"; - string pathTestFile3 = root + "test3.txt"; - string testFile1HexName = "1234567890abcde1"; - string testFile2HexName = "1234567890abcde2"; - string testFile3HexName = "1234567890abcde3"; - SaveStringToFile(pathTestFile1, "h"); - SaveStringToFile(pathTestFile2, "hello"); - SaveStringToFile(pathTestFile3, "hello world"); - BJsonCachedEntity cachedEntity(UniqueFd(open(pathManageFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - - // 生成三条有用数据并写入索引文件 - map> info; - info.emplace(testFile1HexName, make_pair(pathTestFile1, GetFileStat(pathTestFile1))); - info.emplace(testFile2HexName, make_pair(pathTestFile2, GetFileStat(pathTestFile2))); - info.emplace(testFile3HexName, make_pair(pathTestFile3, GetFileStat(pathTestFile3))); - cache.SetExtManage(info); - - // 向索引文件中的三条记录分别追加0、1、2条硬链接信息 - set hardLinks1, hardLinks2, hardLinks3; - cache.SetHardLinkInfo(testFile1HexName, hardLinks1); - hardLinks2.emplace(root + "testFile2hardlink1"); - cache.SetHardLinkInfo(testFile2HexName, hardLinks2); - hardLinks3.emplace(root + "testFile3hardlink1"); - hardLinks3.emplace(root + "testFile3hardlink2"); - cache.SetHardLinkInfo(testFile3HexName, hardLinks3); - - // 预置结果集,用以在读取索引文件后做结果判断 - set resultFileName {testFile1HexName, testFile2HexName, testFile3HexName}; - - // 读取索引文件内容并做结果判断 - auto fileNames = cache.GetExtManage(); - EXPECT_EQ(fileNames.size(), info.size()); - EXPECT_EQ(fileNames, resultFileName); - auto fileInfo = cache.GetExtManageInfo(); - EXPECT_EQ(fileInfo.size(), info.size()); - EXPECT_TRUE(IsEqual(fileInfo, info)); - // 传入无效文件名"00000000",测试读取文件硬链接接口是否正确返回 - auto testFile0HardLinks = cache.GetHardLinkInfo("00000000"); - EXPECT_TRUE(testFile0HardLinks.empty()); - auto testFile1HardLinks = cache.GetHardLinkInfo(testFile1HexName); - EXPECT_TRUE(testFile1HardLinks.empty()); - auto testFile2HardLinks = cache.GetHardLinkInfo(testFile2HexName); - EXPECT_EQ(testFile2HardLinks, hardLinks2); - auto testFile3HardLinks = cache.GetHardLinkInfo(testFile3HexName); - EXPECT_EQ(testFile3HardLinks, hardLinks3); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0400"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0500 - * @tc.name: b_json_entity_ext_manage_0500 - * @tc.desc: 通过向接口SetExtManage传入包含三条信息的map参数,测试对索引文件的操作是否正确。 - * 0:通过向索引文件写入3条有效数据模拟覆盖对索引文件的(无穷)内容的测试覆盖 - * 0:通过向索引文件的记录一写入0条、记录二写入1条、记录三写入2条有效硬链接数据模拟对索引文件含 - * 有硬链接(空、有、无穷)个的测试覆盖 - * 0:通过传入和源文件相同stat信息向索引文件中对应记录添加硬链接 - * 1:调用接口SetExtManage,向索引文件写入数据 - * 2:调用接口GetExtManage,从索引文件读出文件名数据 - * 3:调用接口GetExtManageInfo,从索引文件读出文件详细数据(含文件名和对应文件的stat数据) - * 4:判断读出的文件名集合/文件详细数据记录个数是否和写入时相等 - * 5:判断读出的文件名集合/文件详细数据记录内容是否和写入时相等 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0500, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0500"; - try { - // 预置文件数据 - // 索引文件pathManageFile1/2/3, 测试文件路径pathTestFile1/2/3, 测试文件名testFile1/2/3HexName - TestManager tm("b_json_entity_ext_manage_0500"); - string root = tm.GetRootDirCurTest(); - string pathManageFile = root + "manage.json"; - string pathTestFile1 = root + "test1.txt"; - string pathTestFile2 = root + "test2.txt"; - string pathTestFile3 = root + "test3.txt"; - string testFile1HexName = "1234567890abcde1"; - string testFile2HexName = "1234567890abcde2"; - string testFile3HexName = "1234567890abcde3"; - SaveStringToFile(pathTestFile1, "h"); - SaveStringToFile(pathTestFile2, "hello"); - SaveStringToFile(pathTestFile3, "hello world"); - BJsonCachedEntity cachedEntity(UniqueFd(open(pathManageFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - - // 生成三条有用数据并写入索引文件 - // 通过重用原始文件的stat向该记录追加(0/1/2)条硬链接文件信息 - map> info; - struct stat sta = {}; - info.emplace(testFile1HexName, make_pair(pathTestFile1, GetFileStat(pathTestFile1))); - info.emplace(testFile2HexName, make_pair(pathTestFile2, sta = GetFileStat(pathTestFile2))); - info.emplace("testFile2hardlink1", make_pair(root + "testFile2hardlink1", sta)); - info.emplace(testFile3HexName, make_pair(pathTestFile3, sta = GetFileStat(pathTestFile3))); - info.emplace("testFile3hardlink1", make_pair(root + "testFile3hardlink1", sta)); - info.emplace("testFile3hardlink2", make_pair(root + "testFile3hardlink2", sta)); - cache.SetExtManage(info); - - // 预置结果集,用以在读取索引文件后做结果判断 - // 将info中的硬链接信息删除,保留原始文件信息,作为后续结果值判断的比较对象 - info.erase("testFile2hardlink1"); - info.erase("testFile3hardlink1"); - info.erase("testFile3hardlink2"); - set hardLinks2 {root + "testFile2hardlink1"}; - set hardLinks3 {root + "testFile3hardlink1", root + "testFile3hardlink2"}; - set resultFileName {testFile1HexName, testFile2HexName, testFile3HexName}; - - // 读取索引文件内容并做结果判断 - auto fileNames = cache.GetExtManage(); - EXPECT_EQ(fileNames.size(), 3ul); - EXPECT_EQ(fileNames, resultFileName); - auto fileInfo = cache.GetExtManageInfo(); - EXPECT_EQ(fileInfo.size(), info.size()); - EXPECT_TRUE(IsEqual(fileInfo, info)); - auto testFile1HardLinks = cache.GetHardLinkInfo(testFile1HexName); - EXPECT_TRUE(testFile1HardLinks.empty()); - auto testFile2HardLinks = cache.GetHardLinkInfo(testFile2HexName); - EXPECT_EQ(testFile2HardLinks, hardLinks2); - auto testFile3HardLinks = cache.GetHardLinkInfo(testFile3HexName); - EXPECT_EQ(testFile3HardLinks, hardLinks3); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0500"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0600 - * @tc.name: b_json_entity_ext_manage_0600 - * @tc.desc: 测试SetExtManage接口中的FindLinks在设备号或INode数目为0时能否成功通过GetExtManage获取相关信息 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0600, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0600"; - try { - map> mp = {{"key", {"first", {}}}}; - Json::Value jv; - BJsonEntityExtManage extMg(jv); - - extMg.SetExtManage(mp); - set ss = extMg.GetExtManage(); - EXPECT_EQ(ss.size(), 1); - - mp.at("key").second.st_dev = 1; - extMg.SetExtManage(mp); - ss = extMg.GetExtManage(); - EXPECT_EQ(ss.size(), 1); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0600"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0700 - * @tc.name: b_json_entity_ext_manage_0700 - * @tc.desc: 测试GetExtManageInfo在Json数据不为数组时能否成功返回空map - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0700, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0700"; - try { - string_view sv = R"({"key":1})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - auto mp = cache.GetExtManageInfo(); - EXPECT_TRUE(mp.empty()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0700"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0800 - * @tc.name: b_json_entity_ext_manage_0800 - * @tc.desc: 测试GetExtManageInfo在Json数据为数组且仅有一个键不为information的对象时能否成功返回空map - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0800, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0800"; - try { - string_view sv = R"([{"key":1}])"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - auto mp = cache.GetExtManageInfo(); - EXPECT_TRUE(mp.empty()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0800"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_ext_manage_0900 - * @tc.name: b_json_entity_ext_manage_0900 - * @tc.desc: 测试SetHardLinkInfo接口和GetHardLinkInfo接口在不符合相关条件时能否成功返回false和空set - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0900, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0900"; - try { - string_view sv = R"({"key":1})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - EXPECT_FALSE(cache.SetHardLinkInfo("", {})); - - Json::Value jv; - BJsonEntityExtManage extMg(jv); - EXPECT_FALSE(extMg.SetHardLinkInfo("1", {})); - - EXPECT_FALSE(cache.SetHardLinkInfo("1", {})); - - EXPECT_EQ(cache.GetHardLinkInfo(""), set()); - - EXPECT_EQ(extMg.GetHardLinkInfo("1"), set()); - - EXPECT_EQ(cache.GetHardLinkInfo("1"), set()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0900"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_json/b_json_entity_extension_config_test.cpp b/tests/unittests/backup_utils/b_json/b_json_entity_extension_config_test.cpp deleted file mode 100644 index 80f7a51ae..000000000 --- a/tests/unittests/backup_utils/b_json/b_json_entity_extension_config_test.cpp +++ /dev/null @@ -1,582 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_json/b_json_cached_entity.h" -#include "b_json/b_json_entity_caps.h" -#include "b_json/b_json_entity_extension_config.h" -#include "b_process/b_process.h" -#include "b_resources/b_constants.h" -#include "directory_ex.h" -#include "file_ex.h" -#include "parameter.h" -#include "test_manager.h" -#include "json/value.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class BJsonEntityExtensionConfigTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -static vector DEFAULT_INCLUDE_DIR = { - "data/storage/el2/database/", - "data/storage/el2/base/files/", - "data/storage/el2/base/preferences/", - "data/storage/el2/base/haps/*/database/", - "data/storage/el2/base/haps/*/base/files/", - "data/storage/el2/base/haps/*/base/preferences/", -}; -static vector DEFAULT_EXCLUDE_DIR = {}; - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0100 - * @tc.name: b_json_entity_extension_config_0100 - * @tc.desc: 不包含includes和excludes - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0100"; - try { - TestManager tm("b_json_entity_extension_config_0100"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile(pathConfigFile, ""); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector includes = cache.GetIncludes(); - EXPECT_EQ(includes, DEFAULT_INCLUDE_DIR); - vector excludes = cache.GetExcludes(); - EXPECT_EQ(excludes, DEFAULT_EXCLUDE_DIR); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0100"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0200 - * @tc.name: b_json_entity_extension_config_0200 - * @tc.desc: json文件中只包含includes - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0200, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0200"; - try { - TestManager tm("b_json_entity_extension_config_0200"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile(pathConfigFile, R"({"includes":["", "", ""]})"); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector includes = cache.GetIncludes(); - vector includesExpect = {"", "", ""}; - EXPECT_EQ(includes, includesExpect); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0200"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0300 - * @tc.name: b_json_entity_extension_config_0300 - * @tc.desc: json文件中只包含excludes - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0300, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0300"; - try { - TestManager tm("b_json_entity_extension_config_0300"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile(pathConfigFile, R"({"excludes":["", "", ""]})"); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector excludes = cache.GetExcludes(); - vector excludesExpect = {"", "", ""}; - EXPECT_EQ(excludes, excludesExpect); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0300"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0400 - * @tc.name: b_json_entity_extension_config_0400 - * @tc.desc: 同时包含includes和excludes - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0400, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0400"; - try { - TestManager tm("b_json_entity_extension_config_0400"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile(pathConfigFile, R"({"includes":["", "", ""], "excludes":["", "", ""]})"); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector includes = cache.GetIncludes(); - vector includesExpect = {"", "", ""}; - EXPECT_EQ(includes, includesExpect); - vector excludes = cache.GetExcludes(); - vector excludesExpect = {"", "", ""}; - EXPECT_EQ(excludes, excludesExpect); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0400"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0500 - * @tc.name: b_json_entity_extension_config_0500 - * @tc.desc: json文件中标签为特殊字符 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0500, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0500"; - try { - TestManager tm("b_json_entity_extension_config_0500"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile(pathConfigFile, R"({"%#$%445":["", "", ""]})"); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector includes = cache.GetIncludes(); - vector includesExpect = {DEFAULT_INCLUDE_DIR}; - EXPECT_EQ(includes, includesExpect); - vector excludes = cache.GetExcludes(); - vector excludesExpect = {DEFAULT_EXCLUDE_DIR}; - EXPECT_EQ(excludes, excludesExpect); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0500"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0600 - * @tc.name: b_json_entity_extension_config_0600 - * @tc.desc: json文件中标签为中文汉字 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0600, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0600"; - try { - TestManager tm("b_json_entity_extension_config_0600"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile(pathConfigFile, R"({"测试代码":["", "", ""]})"); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector includes = cache.GetIncludes(); - EXPECT_EQ(includes, DEFAULT_INCLUDE_DIR); - vector excludes = cache.GetExcludes(); - EXPECT_EQ(excludes, DEFAULT_EXCLUDE_DIR); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0600"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0700 - * @tc.name: b_json_entity_extension_config_0700 - * @tc.desc: json文件中无标签 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0700, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0700"; - try { - TestManager tm("b_json_entity_extension_config_0700"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile(pathConfigFile, R"({"":["", "", ""]})"); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector includes = cache.GetIncludes(); - EXPECT_EQ(includes, DEFAULT_INCLUDE_DIR); - vector excludes = cache.GetExcludes(); - EXPECT_EQ(excludes, DEFAULT_EXCLUDE_DIR); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0700"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0800 - * @tc.name: b_json_entity_extension_config_0800 - * @tc.desc: json文件标签中有异常引号 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0800, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0800"; - try { - TestManager tm("b_json_entity_extension_config_0800"); - - string root = tm.GetRootDirCurTest(); - string pathConfigFile = root + "config.json"; - SaveStringToFile( - pathConfigFile, - R"({"includes":["", "", ""], "excludes":["", "", ""], """""""""""""""""""""""""""""""""""""""""""""""""":[]})"); - - BJsonCachedEntity cachedEntity(UniqueFd(open(pathConfigFile.data(), O_RDONLY, 0))); - auto cache = cachedEntity.Structuralize(); - vector includes = cache.GetIncludes(); - EXPECT_EQ(includes, DEFAULT_INCLUDE_DIR); - vector excludes = cache.GetExcludes(); - EXPECT_EQ(excludes, DEFAULT_EXCLUDE_DIR); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0800"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_0900 - * @tc.name: b_json_entity_extension_config_0900 - * @tc.desc: 测试GetJSonSource接口能否在非service进程下正确读取backup_config.json - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_0900, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_0900"; - try { - string jsonContent = R"({"allowToBackupRestore":true})"; - auto [bFatalErr, ret] = BProcess::ExecuteCmd({"mkdir", "-p", BConstants::BACKUP_CONFIG_EXTENSION_PATH}); - EXPECT_FALSE(bFatalErr); - EXPECT_EQ(ret, 0); - string jsonFilePath = string(BConstants::BACKUP_CONFIG_EXTENSION_PATH).append(BConstants::BACKUP_CONFIG_JSON); - SaveStringToFile(jsonFilePath, jsonContent); - string_view sv = R"({"allowToBackupRestore":false})"; - SetMockParameter(true); - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - string jsonRead = cache.GetJSonSource(sv, any()); - EXPECT_EQ(jsonRead, jsonContent); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetJSonSource."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_0900"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1000 - * @tc.name: b_json_entity_extension_config_1000 - * @tc.desc: 测试GetJSonSource接口能否在service进程下正确读取backup_config.json - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1000, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1000"; - try { - string bundleName = "com.example.app2backup"; - string jsonFileDir = string(BConstants::SA_BUNDLE_BACKUP_ROOT_DIR).append(bundleName); - string jsonContent = R"({"allowToBackupRestore":true})"; - auto [bFatalErr, ret] = BProcess::ExecuteCmd({"mkdir", "-p", jsonFileDir}); - EXPECT_FALSE(bFatalErr); - EXPECT_EQ(ret, 0); - string jsonFilePath = jsonFileDir.append("/").append(BConstants::BACKUP_CONFIG_JSON); - SaveStringToFile(jsonFilePath, jsonContent); - uid_t currUid = getuid(); - setuid(BConstants::BACKUP_UID); - string_view sv = R"({"allowToBackupRestore":false})"; - SetMockParameter(true); - BJsonCachedEntity cachedEntity(sv, bundleName); - auto cache = cachedEntity.Structuralize(); - string jsonRead = cache.GetJSonSource(sv, bundleName); - setuid(currUid); - EXPECT_EQ(jsonRead, jsonContent); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetJSonSource."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1000"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1100 - * @tc.name: b_json_entity_extension_config_1100 - * @tc.desc: 测试GetJSonSource接口能否在backup.debug.overrideExtensionConfig为false的情况下保持原JSon字符串不变 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1100, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1100"; - try { - string_view sv = R"({"allowToBackupRestore":false})"; - SetMockParameter(false); - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - string jsonRead = cache.GetJSonSource(sv, any()); - EXPECT_EQ(jsonRead, string(sv)); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetJSonSource."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1100"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1200 - * @tc.name: b_json_entity_extension_config_1200 - * @tc.desc: 测试GetIncludes接口在Json数据中键为includes的值不为数组时能否成功返回默认目录 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1200, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1200"; - try { - string_view sv = R"({"includes":1})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - vector vs = cache.GetIncludes(); - EXPECT_EQ(vs, DEFAULT_INCLUDE_DIR); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetIncludes."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1200"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1300 - * @tc.name: b_json_entity_extension_config_1300 - * @tc.desc: 测试GetIncludes接口在Json数据中键为includes的值为数组且数组元素全都不为字符串时能否成功返回空目录 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1300, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1300"; - try { - string_view sv = R"({"includes":[1]})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - vector vs = cache.GetIncludes(); - EXPECT_EQ(vs, vector({""})); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetIncludes."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1300"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1400 - * @tc.name: b_json_entity_extension_config_1400 - * @tc.desc: 测试GetExcludes接口在Json数据中键为excludes的值不为数组时能否成功返回空vector - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1400, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1400"; - try { - string_view sv = R"({"excludes":1})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - vector vs = cache.GetExcludes(); - EXPECT_EQ(vs, vector()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetExcludes."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1400"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1500 - * @tc.name: b_json_entity_extension_config_1500 - * @tc.desc: 测试GetExcludes接口在Json数据中键为excludes的值为数组且数组元素全都不为字符串时能否成功返回空vector - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1500, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1500"; - try { - string_view sv = R"({"excludes":[1]})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - vector vs = cache.GetExcludes(); - EXPECT_EQ(vs, vector()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetExcludes."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1500"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1600 - * @tc.name: b_json_entity_extension_config_1600 - * @tc.desc: 测试GetAllowToBackupRestore接口在Json数据对象nullValue时能否成功返回false - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1600, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1600"; - try { - Json::Value jv(Json::nullValue); - BJsonEntityExtensionConfig extCfg(jv); - EXPECT_FALSE(extCfg.GetAllowToBackupRestore()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetAllowToBackupRestore."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1600"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1700 - * @tc.name: b_json_entity_extension_config_1700 - * @tc.desc: 测试GetAllowToBackupRestore接口在Json数据对象不含allowToBackupRestore键时能否成功返回false - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1700, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1700"; - try { - string_view sv = R"({"allowToBackupRestore_":true})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - EXPECT_FALSE(cache.GetAllowToBackupRestore()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetAllowToBackupRestore."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1700"; -} - -/** - * @tc.number: SUB_backup_b_json_entity_extension_config_1800 - * @tc.name: b_json_entity_extension_config_1800 - * @tc.desc: 测试GetAllowToBackupRestore接口在Json数据对象键为allowToBackupRestore的值不为布尔值时能否成功返回false - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 2 - * @tc.require: I6F3GV - */ -HWTEST_F(BJsonEntityExtensionConfigTest, b_json_entity_extension_config_1800, testing::ext::TestSize.Level2) -{ - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-begin b_json_entity_extension_config_1800"; - try { - string_view sv = R"({"allowToBackupRestore":1})"; - BJsonCachedEntity cachedEntity(sv); - auto cache = cachedEntity.Structuralize(); - EXPECT_FALSE(cache.GetAllowToBackupRestore()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-an exception occurred by GetAllowToBackupRestore."; - } - GTEST_LOG_(INFO) << "BJsonEntityExtensionConfigTest-end b_json_entity_extension_config_1800"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_process/b_process_test.cpp b/tests/unittests/backup_utils/b_process/b_process_test.cpp deleted file mode 100644 index 54f4b5d7e..000000000 --- a/tests/unittests/backup_utils/b_process/b_process_test.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include - -#include - -#include "b_process/b_process.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class BProcessTest : public testing::Test { -public: - static void SetUpTestCase() {}; - static void TearDownTestCase() {}; - void SetUp() override {}; - void TearDown() override {}; -}; - -static bool DetectFatalLog(string_view output) -{ - GTEST_LOG_(INFO) << "DetectFatalLog " << output; - if (output.find("empty archive") != string_view::npos) { - return true; - } - return false; -} - -/** - * @tc.number: SUB_backup_tool_BProcess_0100 - * @tc.name: SUB_backup_tool_BProcess_0100 - * @tc.desc: 测试ExecuteCmd - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 0 - * @tc.require: I6F3GV - */ -HWTEST_F(BProcessTest, SUB_backup_tool_BProcess_0100, testing::ext::TestSize.Level0) -{ - GTEST_LOG_(INFO) << "BProcessTest-begin SUB_backup_tool_BProcess_0100"; - try { - vector argvCf = { - "/system/bin/tar", - "-cf", - "/data/backup/", - }; - auto [bFatalError, ret] = BProcess::ExecuteCmd(argvCf, DetectFatalLog); - EXPECT_NE(ret, 0); - - vector argvTvf = { - "/system/bin/tar", - "-tvf", - "/data/backup/", - }; - auto [bFatalErro1r, retTvf] = BProcess::ExecuteCmd(argvTvf, DetectFatalLog); - EXPECT_NE(retTvf, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BProcessTest-an exception occurred."; - } - GTEST_LOG_(INFO) << "BProcessTest-end SUB_backup_tool_BProcess_0100"; -} -} // namespace OHOS::FileManagement::Backup diff --git a/tests/unittests/backup_utils/b_tarball/b_tarball_cmdline_test.cpp b/tests/unittests/backup_utils/b_tarball/b_tarball_cmdline_test.cpp deleted file mode 100644 index 97a5c4899..000000000 --- a/tests/unittests/backup_utils/b_tarball/b_tarball_cmdline_test.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_tarball/b_tarball_cmdline.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class BTarballCmdlineTest : public testing::Test { -public: - static void SetUpTestCase() {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_b_tarball_cmdline_0100 - * @tc.name: b_tarball_cmdline_0100 - * @tc.desc: 测试BTarballCmdline类构造函数是否成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BTarballCmdlineTest, b_tarball_cmdline_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BTarballCmdlineTest-begin b_tarball_cmdline_0100"; - try { - TestManager tm("b_tarball_cmdline_0100"); - string root = tm.GetRootDirCurTest(); - string_view tarballDir = root; - string_view tarballName = "test.tar"; - - BTarballCmdline tarballCmdline(tarballDir, tarballName); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BTarballCmdlineTest-an exception occurred by BTarballCmdline."; - } - GTEST_LOG_(INFO) << "BTarballCmdlineTest-end b_tarball_cmdline_0100"; -} - -/** - * @tc.number: SUB_b_tarball_cmdline_0200 - * @tc.name: b_tarball_cmdline_0200 - * @tc.desc: 测试BTarballCmdline类Tar函数是否成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BTarballCmdlineTest, b_tarball_cmdline_0200, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BTarballCmdlineTest-begin b_tarball_cmdline_0200"; - try { - // 预置文件和目录 - TestManager tm("b_tarball_cmdline_0200"); - string root = tm.GetRootDirCurTest(); - string_view tarballDir = root; - string_view tarballName = "test.tar"; - string testDir = root + "/testdir"; - if (mkdir(testDir.data(), S_IRWXU) && errno != EEXIST) { - GTEST_LOG_(INFO) << " invoked mkdir failure, errno :" << errno; - throw BError(errno); - } - string strFile = root + tarballName.data(); - UniqueFd fd(open(strFile.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - if (fd < 0) { - GTEST_LOG_(INFO) << " invoked open failure, errno :" << errno; - throw BError(errno); - } - - string aFile = testDir + "/a.txt"; - string bFile = testDir + "/b.txt"; - SaveStringToFile(aFile, "hello"); - SaveStringToFile(bFile, "world"); - vector includes {testDir}; - vector excludes {bFile}; - - // 调用tar打包 - BTarballCmdline tarballCmdline(tarballDir, tarballName); - tarballCmdline.Tar(root, includes, excludes); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BTarballCmdlineTest-an exception occurred by BTarballCmdline."; - } - GTEST_LOG_(INFO) << "BTarballCmdlineTest-end b_tarball_cmdline_0200"; -} - -/** - * @tc.number: SUB_b_tarball_cmdline_0300 - * @tc.name: b_tarball_cmdline_0300 - * @tc.desc: 测试BTarballCmdline类Untar函数是否成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BTarballCmdlineTest, b_tarball_cmdline_0300, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BTarballCmdlineTest-begin b_tarball_cmdline_0300"; - try { - // 预置文件和目录 - TestManager tm("b_tarball_cmdline_0300"); - string root = tm.GetRootDirCurTest(); - string_view tarballDir = root; - string_view tarballName = "test.tar"; - string testUntarDir = root + "/untardir"; - if (mkdir(testUntarDir.data(), S_IRWXU) && errno != EEXIST) { - GTEST_LOG_(INFO) << " invoked mkdir failure, errno :" << errno; - throw BError(errno); - } - // 调用tar打包 - BTarballCmdline tarballCmdline(tarballDir, tarballName); - tarballCmdline.Untar(testUntarDir); - - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BTarballCmdlineTest-an exception occurred by BTarballCmdline."; - } - GTEST_LOG_(INFO) << "BTarballCmdlineTest-end b_tarball_cmdline_0300"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_tarball/b_tarball_factory_test.cpp b/tests/unittests/backup_utils/b_tarball/b_tarball_factory_test.cpp deleted file mode 100644 index d0bd3d783..000000000 --- a/tests/unittests/backup_utils/b_tarball/b_tarball_factory_test.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include -#include - -#include "b_tarball/b_tarball_factory.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class BTarballFactoryTest : public testing::Test { -public: - static void SetUpTestCase() {}; - static void TearDownTestCase() {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.number: SUB_b_tarball_factory_0100 - * @tc.name: b_tarball_factory_0100 - * @tc.desc: 测试BTarballFactory类create函数是否成功 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BTarballFactoryTest, b_tarball_factory_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BTarballFactoryTest-begin b_tarball_factory_0100"; - try { - // 预置路径 - TestManager tm("b_tarball_factory_0100"); - string root = tm.GetRootDirCurTest(); - string implType = "cmdline"; - string tarballPath = root + "/test.tar"; - SaveStringToFile(tarballPath, "data/storage/el2/database/"); - // 调用create获取打包解包能力 - auto tarballTar = BTarballFactory::Create(implType, tarballPath); - GTEST_LOG_(INFO) << "BTarballFactoryTest-tar"; - (tarballTar->tar)("/", {}, {"/data/storage/el2/database/", {}}); - GTEST_LOG_(INFO) << "BTarballFactoryTest-untar"; - (tarballTar->untar)("/"); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BTarballFactoryTest-an exception occurred by BTarballFactory."; - } - GTEST_LOG_(INFO) << "BTarballFactoryTest-end b_tarball_factory_0100"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/utils/BUILD.gn b/tests/utils/BUILD.gn deleted file mode 100644 index 15e364007..000000000 --- a/tests/utils/BUILD.gn +++ /dev/null @@ -1,34 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -config("test_util_public_config") { - include_dirs = [ "include" ] -} - -ohos_static_library("backup_test_utils") { - testonly = true - - sources = [ "src/test_manager.cpp" ] - - public_configs = [ ":test_util_public_config" ] - - deps = [ "${path_backup}/utils:backup_utils" ] - public_deps = [ "${path_googletest}:gmock_main" ] - - use_exceptions = true - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/tests/utils/include/test_manager.h b/tests/utils/include/test_manager.h deleted file mode 100644 index 034658ba5..000000000 --- a/tests/utils/include/test_manager.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_TEST_MANAGER_H -#define OHOS_FILEMGMT_BACKUP_TEST_MANAGER_H - -#include - -namespace OHOS::FileManagement::Backup { -class TestManager { -public: - explicit TestManager(std::string functionName); - ~TestManager(); - - /** - * @brief 获取当前测试用例指定根目录 - * - * @return std::string 根目录 - */ - std::string GetRootDirCurTest() const; - -private: - std::string rootDirCurTest_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_TEST_MANAGER_H diff --git a/tests/utils/src/test_manager.cpp b/tests/utils/src/test_manager.cpp deleted file mode 100644 index 7bf577ec4..000000000 --- a/tests/utils/src/test_manager.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include "directory_ex.h" -#include "test_manager.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -TestManager::TestManager(std::string functionName) -{ - rootDirCurTest_ = "/data/test/backup/" + functionName + "/"; - // REM:先删后创建 - if (bool created = ForceCreateDirectory(rootDirCurTest_); !created) { - throw std::system_error(errno, std::system_category()); - } -} - -TestManager::~TestManager() -{ - ForceRemoveDirectory(rootDirCurTest_); -} - -string TestManager::GetRootDirCurTest() const -{ - return rootDirCurTest_; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/BUILD.gn b/tools/backup_tool/BUILD.gn deleted file mode 100644 index 691437a6d..000000000 --- a/tools/backup_tool/BUILD.gn +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -ohos_executable("backup_tool") { - sources = [ - "src/main.cpp", - "src/tools_op.cpp", - "src/tools_op_backup.cpp", - "src/tools_op_check_sa.cpp", - "src/tools_op_help.cpp", - "src/tools_op_restore.cpp", - ] - - defines = [ - "LOG_DOMAIN=0xD004304", - "LOG_TAG=\"BackupTool\"", - ] - - include_dirs = [ "include" ] - - external_deps = [ - "app_file_service:backup_kit_inner", - "hitrace_native:hitrace_meter", - ] - - deps = [ "${path_backup}/utils/:backup_utils" ] - - use_exceptions = true - install_enable = true - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/tools/backup_tool/include/tools_op.h b/tools/backup_tool/include/tools_op.h deleted file mode 100644 index 79b063c1e..000000000 --- a/tools/backup_tool/include/tools_op.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_TOOLS_OP_H -#define OHOS_FILEMGMT_BACKUP_TOOLS_OP_H - -#include -#include -#include -#include -#include - -namespace OHOS::FileManagement::Backup { -class ToolsOp { -public: - using CRefVStrView = const std::vector &; - struct CmdInfo { - std::string paramName; - bool repeatable = false; - }; - - struct Descriptor { - // 命令名,必填 - std::vector opName; - // 参数,选填 - std::vector argList; - // 命令帮助语句,选填 - std::function funcGenHelpMsg; - // 命令执行主体,必填 - std::function> &args)> funcExec; - }; - - /** - * @brief 构造一个操作 - * - * @param desc 操作具体信息 - */ - explicit ToolsOp(Descriptor &&desc) : desc_(std::move(desc)) {} - - /** - * @brief 获取当前操作的名称。操作由多条字符串构成时,之间由空格隔开 - * - * @return const std::string 当前操作的名称 - */ - const std::string GetName() const; - - /** - * @brief 获取当前操作的参数 - * - * @return std::vector 当前参数的向量 - */ - const std::vector GetParams() const - { - return desc_.argList; - } - - /** - * @brief 获取当前操作的原始具体信息 - * - * @return const Descriptor& 当前操作的原始具体信息 - */ - const Descriptor &GetDescriptor() const - { - return desc_; - } - - /** - * @brief 获取所有操作 - * - * @return const std::vector& 所有操作 - */ - static const std::vector &GetAllOperations() - { - return ToolsOp::opsAvailable_; - } - - /** - * @brief 注册一个操作 - * - * @param op 操作 - * @return true 注册成功 - * @return false 注册失败 - */ - static bool Register(ToolsOp &&op); - - /** - * @brief 将当前操作与主函数给定的操作相匹配(大小写敏感) - * - * @param op 给定操作 - * @return true 匹配成功 - * @return false 匹配失败 - */ - bool TryMatch(CRefVStrView op) const; - - /** - * @brief 使用主函数给定的参数表执行当前操作 - * - * @param args 给定参数表 - * @return int 错误码(0 表示成功,非零表示失败) - */ - int Execute(std::map> mapArg) const; - -private: - Descriptor desc_; - static inline std::vector opsAvailable_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_TOOLS_OP_H \ No newline at end of file diff --git a/tools/backup_tool/src/main.cpp b/tools/backup_tool/src/main.cpp deleted file mode 100644 index ae8d71131..000000000 --- a/tools/backup_tool/src/main.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "errors.h" -#include "tools_op.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace OHOS::FileManagement::Backup { -using namespace std; - -optional>> GetArgsMap(int argc, char *const argv[], const vector &argList) -{ - int i = 0; - map mapOptToName; - vector vecLongOptions; - for (auto &&arg : argList) { - mapOptToName[i] = arg.paramName; - vecLongOptions.emplace_back(option { - .name = arg.paramName.c_str(), - .has_arg = required_argument, - .flag = nullptr, - .val = i++, - }); - } - vecLongOptions.emplace_back(option {nullptr, 0, nullptr, 0}); - - int opt = 0; - int options_index = 0; - map> mapArgToVals; - while ((opt = getopt_long(argc, argv, "", vecLongOptions.data(), &options_index)) != -1) { - if (opt == '?') { - // "我们匹配到了一个奇怪的命令 返回 nullopt,getopt_long 在opterr 未被赋值0时 会自动打印未被定义参数到终端" - return nullopt; - } - string argName = mapOptToName[opt]; - if (mapArgToVals.find(argName) != mapArgToVals.end() && argList[opt].repeatable == true) { - mapArgToVals[argName].emplace_back(optarg); - } else if (mapArgToVals.find(argName) != mapArgToVals.end()) { - fprintf(stderr, "%s can only be entered once, but you repeat it.\n", argName.c_str()); - return nullopt; - } else { - mapArgToVals.emplace(argName, vector {optarg}); - } - } - return mapArgToVals; -} - -int ParseOpAndExecute(int argc, char *const argv[]) -{ - int flag = -1; - for (int i = 1; i < argc; i++) { - // 暂存 {argv[1]...argv[i]}; - vector curOp; - for (int j = 1; j <= i; ++j) { - curOp.emplace_back(argv[j]); - } - - // 尝试匹配当前命令,成功后执行 - auto tryOpSucceed = [&curOp](const ToolsOp &op) { return op.TryMatch(curOp); }; - auto &&opeartions = ToolsOp::GetAllOperations(); - auto matchedOp = find_if(opeartions.begin(), opeartions.end(), tryOpSucceed); - if (matchedOp != opeartions.end()) { - vector argList = matchedOp->GetParams(); - optional>> mapNameToArgs = GetArgsMap(argc, argv, argList); - if (mapNameToArgs.has_value()) { - flag = matchedOp->Execute(mapNameToArgs.value()); - } - } - } - if (flag != 0) { - printf("backup_tool: missing operand\nTry 'backup_tool help' for more information.\n"); - } - return flag; -} -} // namespace OHOS::FileManagement::Backup - -int main(int argc, char *const argv[]) -{ - return OHOS::FileManagement::Backup::ParseOpAndExecute(argc, argv); -} \ No newline at end of file diff --git a/tools/backup_tool/src/tools_op.cpp b/tools/backup_tool/src/tools_op.cpp deleted file mode 100644 index 782de8c2a..000000000 --- a/tools/backup_tool/src/tools_op.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "tools_op.h" - -#include -#include - -namespace OHOS::FileManagement::Backup { -using namespace std; - -const std::string ToolsOp::GetName() const -{ - std::stringstream ss; - - auto &&allSubOps = desc_.opName; - for (size_t j = 0; j < allSubOps.size(); ++j) { - ss << allSubOps[j]; - if (j != allSubOps.size() - 1) { - ss << ' '; - } - } - - return ss.str(); -} - -bool ToolsOp::Register(ToolsOp &&op) -{ - auto &&opName = op.GetDescriptor().opName; - auto isIncorrect = [&opName](const std::string_view &subOp) { - std::vector patterns { - "\\W", // 匹配任意不是字母、数字、下划线的字符 - "^$", // 匹配空串 - }; - - for (auto subOp : opName) { - for (auto pattern : patterns) { - std::regex re(pattern); - if (std::regex_search(string(subOp), re)) { - fprintf(stderr, "Sub-op '%s' failed to pass regex '%s'\n", subOp.data(), pattern.c_str()); - return true; - } - } - } - - return false; - }; - if (std::any_of(opName.begin(), opName.end(), isIncorrect)) { - fprintf(stderr, "Failed to register an illegal operation '%s'\n", op.GetName().c_str()); - return false; - } - - ToolsOp::opsAvailable_.emplace_back(std::move(op)); - - // sort with ascending order - std::sort(opsAvailable_.begin(), opsAvailable_.end(), [](const ToolsOp &lop, const ToolsOp &rop) { - return lop.desc_.opName < rop.desc_.opName; - }); - return true; -} - -bool ToolsOp::TryMatch(CRefVStrView op) const -{ - return op == desc_.opName; -} - -int ToolsOp::Execute(map> args) const -{ - if (!desc_.funcExec) { - fprintf(stderr, "Incomplete operation: executor is missing\n"); - return -EPERM; - } - return desc_.funcExec(args); -} -} // namespace OHOS::FileManagement::Backup diff --git a/tools/backup_tool/src/tools_op_backup.cpp b/tools/backup_tool/src/tools_op_backup.cpp deleted file mode 100644 index 72f281865..000000000 --- a/tools/backup_tool/src/tools_op_backup.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include "b_error/b_error.h" -#include "b_filesystem/b_file.h" -#include "b_json/b_json_entity_ext_manage.h" -#include "b_resources/b_constants.h" -#include "backup_kit_inner.h" -#include "base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h" -#include "service_proxy.h" -#include "tools_op.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class Session { -public: - void UpdateBundleReceivedFiles(const BundleName &bundleName, const string &fileName) - { - lock_guard lk(lock_); - bundleStatusMap_[bundleName].receivedFile.insert(fileName); - TryClearBundleOfMap(bundleName); - } - - void SetIndexFiles(const BundleName &bundleName, UniqueFd fd) - { - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - lock_guard lk(lock_); - bundleStatusMap_[bundleName].indexFile = cache.GetExtManage(); - } - - void TryNotify(bool flag = false) - { - if (flag == true) { - ready_ = true; - cv_.notify_all(); - } else if (bundleStatusMap_.size() == 0 && cnt_ == 0) { - ready_ = true; - cv_.notify_all(); - } - } - - void UpdateBundleFinishedCount() - { - lock_guard lk(lock_); - cnt_--; - } - - void SetBundleFinishedCount(uint32_t cnt) - { - cnt_ = cnt; - } - - void Wait() - { - unique_lock lk(lock_); - cv_.wait(lk, [&] { return ready_; }); - } - - unique_ptr session_ = {}; - -private: - struct BundleStatus { - set receivedFile; - set indexFile; - }; - - void TryClearBundleOfMap(const BundleName &bundleName) - { - if (bundleStatusMap_[bundleName].indexFile == bundleStatusMap_[bundleName].receivedFile) { - bundleStatusMap_.erase(bundleName); - } - } - - map bundleStatusMap_; - mutable condition_variable cv_; - mutex lock_; - bool ready_ = false; - uint32_t cnt_ {0}; -}; - -static string GenHelpMsg() -{ - return "\t\tThis operation helps to backup application data.\n" - "\t\t--isLocal\t\t This parameter should be true or flase; true: local backup false: others.\n" - "\t\t--pathCapFile\t\t This parameter should be the path of the capability file.\n" - "\t\t--bundle\t\t This parameter is bundleName."; -} - -static void OnFileReady(shared_ptr ctx, const BFileInfo &fileInfo, UniqueFd fd) -{ - printf("FileReady owner = %s, fileName = %s, sn = %u, fd = %d\n", fileInfo.owner.c_str(), fileInfo.fileName.c_str(), - fileInfo.sn, fd.Get()); - string tmpPath = string(BConstants::BACKUP_TOOL_RECEIVE_DIR) + fileInfo.owner; - if (access(tmpPath.data(), F_OK) != 0 && mkdir(tmpPath.data(), S_IRWXU) != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - if (!regex_match(fileInfo.fileName, regex("^[0-9a-zA-Z_.]+$"))) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "Filename is not alphanumeric"); - } - UniqueFd fdLocal(open((tmpPath + "/" + fileInfo.fileName).data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU)); - if (fdLocal < 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - BFile::SendFile(fdLocal, fd); - if (fileInfo.fileName == BConstants::EXT_BACKUP_MANAGE) { - ctx->SetIndexFiles(fileInfo.owner, move(fd)); - } else { - ctx->UpdateBundleReceivedFiles(fileInfo.owner, fileInfo.fileName); - } - ctx->TryNotify(); -} - -static void OnBundleStarted(shared_ptr ctx, ErrCode err, const BundleName name) -{ - printf("BundleStarted errCode = %d, BundleName = %s\n", err, name.c_str()); - if (err != 0) { - ctx->UpdateBundleFinishedCount(); - ctx->TryNotify(); - } -} - -static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleName name) -{ - printf("BundleFinished errCode = %d, BundleName = %s\n", err, name.c_str()); - ctx->UpdateBundleFinishedCount(); - ctx->TryNotify(); -} - -static void OnAllBundlesFinished(shared_ptr ctx, ErrCode err) -{ - if (err == 0) { - printf("backup successful\n"); - } else { - printf("Failed to Unplanned Abort error: %d\n", err); - ctx->TryNotify(true); - return; - } - ctx->TryNotify(); -} - -static void OnBackupServiceDied(shared_ptr ctx) -{ - printf("backupServiceDied\n"); - ctx->TryNotify(true); -} - -static void BackupToolDirSoftlinkToBackupDir() -{ - // 判断BConstants::BACKUP_TOOL_LINK_DIR 是否是软链接 - if (access(BConstants::BACKUP_TOOL_LINK_DIR.data(), F_OK) == 0) { - struct stat inStat = {}; - if (lstat(BConstants::BACKUP_TOOL_LINK_DIR.data(), &inStat) == -1) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - - if ((inStat.st_mode & S_IFMT) == S_IFLNK) { - return; - } - // 非软连接删除重新创建 - if (!ForceRemoveDirectory(BConstants::BACKUP_TOOL_LINK_DIR.data())) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - } - - if (access(BConstants::SA_BUNDLE_BACKUP_TOOL_DIR.data(), F_OK) != 0 && - mkdir(BConstants::SA_BUNDLE_BACKUP_TOOL_DIR.data(), S_IRWXU) != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - if (symlink(BConstants::SA_BUNDLE_BACKUP_TOOL_DIR.data(), BConstants::BACKUP_TOOL_LINK_DIR.data()) == -1) { - HILOGE("failed to create soft link file %{public}s errno : %{public}d", - BConstants::BACKUP_TOOL_LINK_DIR.data(), errno); - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } -} - -static int32_t InitPathCapFile(const string &isLocal, const string &pathCapFile, vector bundleNames) -{ - StartTrace(HITRACE_TAG_FILEMANAGEMENT, "InitPathCapFile"); - // SELinux backup_tool工具/data/文件夹下创建文件夹 SA服务因root用户的自定义标签无写入权限 此处调整为软链接形式 - BackupToolDirSoftlinkToBackupDir(); - - UniqueFd fd(open(pathCapFile.data(), O_RDWR | O_CREAT, S_IRWXU)); - if (fd < 0) { - fprintf(stderr, "Failed to open file error: %d %s\n", errno, strerror(errno)); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - if (isLocal == "true") { - auto proxy = ServiceProxy::GetInstance(); - if (!proxy) { - fprintf(stderr, "Get an empty backup sa proxy\n"); - return -EFAULT; - } - BFile::SendFile(fd, proxy->GetLocalCapabilities()); - } - - if (access((BConstants::BACKUP_TOOL_RECEIVE_DIR).data(), F_OK) != 0 && - mkdir((BConstants::BACKUP_TOOL_RECEIVE_DIR).data(), S_IRWXU) != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - auto ctx = make_shared(); - ctx->session_ = BSessionBackup::Init( - move(fd), bundleNames, - BSessionBackup::Callbacks {.onFileReady = bind(OnFileReady, ctx, placeholders::_1, placeholders::_2), - .onBundleStarted = bind(OnBundleStarted, ctx, placeholders::_1, placeholders::_2), - .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), - .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); - if (ctx->session_ == nullptr) { - printf("Failed to init backup"); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -EPERM; - } - ctx->SetBundleFinishedCount(bundleNames.size()); - int ret = ctx->session_->Start(); - if (ret != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "backup start error"); - } - ctx->Wait(); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return 0; -} - -static int Exec(map> &mapArgToVal) -{ - if (mapArgToVal.find("pathCapFile") == mapArgToVal.end() || mapArgToVal.find("bundles") == mapArgToVal.end() || - mapArgToVal.find("isLocal") == mapArgToVal.end()) { - return -EPERM; - } - return InitPathCapFile(*(mapArgToVal["isLocal"].begin()), *(mapArgToVal["pathCapFile"].begin()), - mapArgToVal["bundles"]); -} - -/** - * @brief The hack behind is that "variable with static storage duration has initialization or a destructor with side - * effects; it shall not be eliminated even if it appears to be unused" -- point 2.[basic.stc.static].c++ draft - * - */ -static bool g_autoRegHack = ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { - .opName = {"backup"}, - .argList = {{ - .paramName = "pathCapFile", - .repeatable = false, - }, - { - .paramName = "bundles", - .repeatable = true, - }, - { - .paramName = "isLocal", - .repeatable = false, - }}, - .funcGenHelpMsg = GenHelpMsg, - .funcExec = Exec, -}}); -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/src/tools_op_check_sa.cpp b/tools/backup_tool/src/tools_op_check_sa.cpp deleted file mode 100644 index daabbb639..000000000 --- a/tools/backup_tool/src/tools_op_check_sa.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "errors.h" -#include "service_proxy.h" -#include "tools_op.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -static string GenHelpMsg() -{ - return "\tThis operation helps to check if the backup sa is available."; -} - -static int Exec(map> &mapArgToVal) -{ - auto proxy = ServiceProxy::GetInstance(); - if (!proxy) { - fprintf(stderr, "Get an empty backup sa proxy\n"); - return -EFAULT; - } - - printf("successful\n"); - return 0; -} - -/** - * @brief The hack behind is that "variable with static storage duration has initialization or a destructor with side - * effects; it shall not be eliminated even if it appears to be unused" -- point 2.[basic.stc.static].c++ draft - * - */ -static bool g_autoRegHack = ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { - .opName = {"check", "sa"}, - .funcGenHelpMsg = GenHelpMsg, - .funcExec = Exec, -}}); -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/src/tools_op_help.cpp b/tools/backup_tool/src/tools_op_help.cpp deleted file mode 100644 index df60b2091..000000000 --- a/tools/backup_tool/src/tools_op_help.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "tools_op.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -static string GenHelpMsg() -{ - return "\t\tThis operation helps to dump the help messages."; -} - -static int Exec(map> &mapArgToVal) -{ - stringstream ss; - auto &&allOps = ToolsOp::GetAllOperations(); - ss << "Usage: backup_tool [OPTION]... [ARG]..." << endl; - for (size_t i = 0; i < allOps.size(); ++i) { - auto desc = allOps[i].GetDescriptor(); - - // echo: \n - ss << allOps[i].GetName(); - - // echo: help msgs\n\n - if (desc.funcGenHelpMsg) { - ss << desc.funcGenHelpMsg() << endl; - } - if (i != allOps.size() - 1) { - ss << endl; - } - } - printf("%s", ss.str().c_str()); - return 0; -} - -/** - * @brief The hack behind is that "variable with static storage duration has initialization or a destructor with side - * effects; it shall not be eliminated even if it appears to be unused" -- point 2.[basic.stc.static].c++ draft - * - */ -static bool g_autoRegHack = ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { - .opName = {"help"}, - .funcGenHelpMsg = GenHelpMsg, - .funcExec = Exec, -}}); -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/src/tools_op_restore.cpp b/tools/backup_tool/src/tools_op_restore.cpp deleted file mode 100644 index 95ba8b840..000000000 --- a/tools/backup_tool/src/tools_op_restore.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_filesystem/b_dir.h" -#include "b_filesystem/b_file.h" -#include "b_json/b_json_entity_ext_manage.h" -#include "b_resources/b_constants.h" -#include "backup_kit_inner.h" -#include "base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h" -#include "errors.h" -#include "service_proxy.h" -#include "tools_op.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -class Session { -public: - void UpdateBundleSendFiles(const BundleName &bundleName, const string &fileName) - { - lock_guard lk(lock_); - bundleStatusMap_[bundleName].sendFile.insert(fileName); - } - - void UpdateBundleSentFiles(const BundleName &bundleName, const string &fileName) - { - lock_guard lk(lock_); - bundleStatusMap_[bundleName].sentFile.insert(fileName); - TryClearBundleOfMap(bundleName); - } - - void ClearBundleOfMap(const BundleName &bundleName) - { - lock_guard lk(lock_); - bundleStatusMap_.erase(bundleName); - } - - void TryNotify(bool flag = false) - { - if (flag == true) { - ready_ = true; - cv_.notify_all(); - } else if (bundleStatusMap_.size() == 0 && cnt_ == 0) { - ready_ = true; - cv_.notify_all(); - } - } - - void UpdateBundleFinishedCount() - { - lock_guard lk(lock_); - cnt_--; - } - - void SetBundleFinishedCount(uint32_t cnt) - { - cnt_ = cnt; - } - - void Wait() - { - unique_lock lk(lock_); - cv_.wait(lk, [&] { return ready_; }); - } - - unique_ptr session_ = {}; - -private: - struct BundleStatus { - set sendFile; - set sentFile; - }; - - void TryClearBundleOfMap(const BundleName &bundleName) - { - if (bundleStatusMap_[bundleName].sendFile == bundleStatusMap_[bundleName].sentFile) { - bundleStatusMap_.erase(bundleName); - } - } - - map bundleStatusMap_; - mutable condition_variable cv_; - mutex lock_; - bool ready_ = false; - uint32_t cnt_ {0}; -}; - -static string GenHelpMsg() -{ - return "\t\tThis operation helps to restore application data.\n" - "\t\t--pathCapFile\t\t This parameter should be the path of the capability file.\n" - "\t\t--bundle\t\t This parameter is bundleName."; -} - -static void OnFileReady(shared_ptr ctx, const BFileInfo &fileInfo, UniqueFd fd) -{ - printf("FileReady owner = %s, fileName = %s, sn = %u, fd = %d\n", fileInfo.owner.c_str(), fileInfo.fileName.c_str(), - fileInfo.sn, fd.Get()); - if (!regex_match(fileInfo.fileName, regex("^[0-9a-zA-Z_.]+$"))) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "Filename is not alphanumeric"); - } - string tmpPath = string(BConstants::BACKUP_TOOL_RECEIVE_DIR) + fileInfo.owner + "/" + fileInfo.fileName; - if (access(tmpPath.data(), F_OK) != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - UniqueFd fdLocal(open(tmpPath.data(), O_RDONLY)); - if (fdLocal < 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - BFile::SendFile(fd, fdLocal); - int ret = ctx->session_->PublishFile(fileInfo); - if (ret != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "PublishFile error"); - } - ctx->UpdateBundleSentFiles(fileInfo.owner, fileInfo.fileName); - ctx->TryNotify(); -} - -static void OnBundleStarted(shared_ptr ctx, ErrCode err, const BundleName name) -{ - printf("BundleStarted errCode = %d, BundleName = %s\n", err, name.c_str()); - if (err != 0) { - ctx->UpdateBundleFinishedCount(); - ctx->ClearBundleOfMap(name); - ctx->TryNotify(); - } -} - -static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleName name) -{ - printf("BundleFinished errCode = %d, BundleName = %s\n", err, name.c_str()); - ctx->UpdateBundleFinishedCount(); - if (err != 0) { - ctx->ClearBundleOfMap(name); - } - ctx->TryNotify(); -} - -static void OnAllBundlesFinished(ErrCode err) -{ - if (err == 0) { - printf("Restore successful\n"); - } else { - printf("Failed to Unplanned Abort error: %d\n", err); - } -} - -static void OnBackupServiceDied(shared_ptr ctx) -{ - printf("backupServiceDied\n"); - ctx->TryNotify(true); -} - -static void RestoreApp(shared_ptr restore, vector &bundleNames) -{ - StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); - if (!restore || !restore->session_) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - for (auto &bundleName : bundleNames) { - if (!regex_match(bundleName, regex("^[0-9a-zA-Z_.]+$"))) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "bundleName is not alphanumeric"); - } - string path = string(BConstants::BACKUP_TOOL_RECEIVE_DIR) + bundleName; - if (access(path.data(), F_OK) != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); - } - const auto [err, filePaths] = BDir::GetDirFiles(path); - if (err != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "error path"); - } - for (auto &filePath : filePaths) { - string fileName = filePath.substr(filePath.rfind("/") + 1); - restore->session_->GetExtFileName(bundleName, fileName); - restore->UpdateBundleSendFiles(bundleName, fileName); - } - } - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); -} - -static int32_t Init(const string &pathCapFile, vector bundleNames) -{ - StartTrace(HITRACE_TAG_FILEMANAGEMENT, "Init"); - auto ctx = make_shared(); - ctx->session_ = BSessionRestore::Init( - bundleNames, - BSessionRestore::Callbacks {.onFileReady = bind(OnFileReady, ctx, placeholders::_1, placeholders::_2), - .onBundleStarted = bind(OnBundleStarted, ctx, placeholders::_1, placeholders::_2), - .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), - .onAllBundlesFinished = OnAllBundlesFinished, - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); - if (ctx->session_ == nullptr) { - printf("Failed to init restore"); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -EPERM; - } - UniqueFd fdRemote(ctx->session_->GetLocalCapabilities()); - if (fdRemote < 0) { - printf("Failed to receive fd"); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return fdRemote; - } - if (lseek(fdRemote, 0, SEEK_SET) == -1) { - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - struct stat stat = {}; - if (fstat(fdRemote, &stat) == -1) { - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - UniqueFd fdLocal(open(pathCapFile.data(), O_WRONLY | O_CREAT, S_IRWXU)); - if (fdLocal < 0) { - fprintf(stderr, "Failed to open file. error: %d %s\n", errno, strerror(errno)); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - if (sendfile(fdLocal, fdRemote, nullptr, stat.st_size) == -1) { - fprintf(stderr, "Failed to Copy file. error: %d %s\n", errno, strerror(errno)); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - ctx->SetBundleFinishedCount(bundleNames.size()); - RestoreApp(ctx, bundleNames); - int ret = ctx->session_->Start(); - if (ret != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "restore start error"); - } - ctx->Wait(); - return 0; -} - -static int Exec(map> &mapArgToVal) -{ - if (mapArgToVal.find("pathCapFile") == mapArgToVal.end() || mapArgToVal.find("bundles") == mapArgToVal.end()) { - return -EPERM; - } - return Init(*(mapArgToVal["pathCapFile"].begin()), mapArgToVal["bundles"]); -} - -/** - * @brief The hack behind is that "variable with static storage duration has initialization or a destructor with side - * effects; it shall not be eliminated even if it appears to be unused" -- point 2.[basic.stc.static].c++ draft - * - */ -static bool g_autoRegHack = ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { - .opName = {"restore"}, - .argList = {{ - .paramName = "pathCapFile", - .repeatable = false, - }, - { - .paramName = "bundles", - .repeatable = true, - }}, - .funcGenHelpMsg = GenHelpMsg, - .funcExec = Exec, -}}); -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/BUILD.gn b/utils/BUILD.gn deleted file mode 100644 index e05117dfb..000000000 --- a/utils/BUILD.gn +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/filemanagement/app_file_service/backup.gni") - -config("utils_private_config") { - defines = [ - "LOG_DOMAIN=0xD004305", - "LOG_TAG=\"BackupUtils\"", - ] -} - -config("utils_public_config") { - include_dirs = [ - "include", - "${path_base}/include", - ] -} - -ohos_shared_library("backup_utils") { - sources = [ - "src/b_encryption/b_encryption.cpp", - "src/b_error/b_error.cpp", - "src/b_filesystem/b_dir.cpp", - "src/b_filesystem/b_file.cpp", - "src/b_json/b_json_entity_ext_manage.cpp", - "src/b_json/b_json_entity_extension_config.cpp", - "src/b_ohos/startup/backup_para.cpp", - "src/b_process/b_guard_cwd.cpp", - "src/b_process/b_guard_signal.cpp", - "src/b_process/b_process.cpp", - "src/b_tarball/b_tarball_cmdline.cpp", - "src/b_tarball/b_tarball_factory.cpp", - ] - - configs = [ ":utils_private_config" ] - public_configs = [ ":utils_public_config" ] - - external_deps = [ "faultloggerd:libdfx_dumpcatcher" ] - - public_deps = [ - "${path_base}:utils", - "${path_distributedfile}/utils/filemgmt_libhilog:filemgmt_libhilog", - "${path_jsoncpp}:jsoncpp", - ] - - include_dirs = [ - "${path_init}/interfaces/innerkits/include/syspara", - "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", - ] - - deps = [ "${path_init}/interfaces/innerkits:libbegetutil" ] - - use_exceptions = true - part_name = "app_file_service" - subsystem_name = "filemanagement" -} diff --git a/utils/include/b_encryption/b_encryption.h b/utils/include/b_encryption/b_encryption.h deleted file mode 100644 index cbd52e061..000000000 --- a/utils/include/b_encryption/b_encryption.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_ENCRYPTION_H -#define OHOS_FILEMGMT_BACKUP_B_ENCRYPTION_H - -namespace OHOS::FileManagement::Backup::BEncryption { -unsigned int CalculateChksum(const char *byteBlock, int blockSize); -} // namespace OHOS::FileManagement::Backup::BEncryption - -#endif // OHOS_FILEMGMT_BACKUP_B_ENCRYPTION_H \ No newline at end of file diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h deleted file mode 100644 index e12434f65..000000000 --- a/utils/include/b_error/b_error.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * 本部件处理错误的原则: - * 原则1:使用异常表示错误,但只有无法处理的问题才算得上是错误,否则只是普通的边界分支; - * 原则2:仅在模块内部使用异常,而在界面层Catch所有异常,从而防止异常扩散; - * 原则3:在注释里通过throw关键字注明可能抛出的异常,通报使用风险。 - */ -#ifndef OHOS_FILEMGMT_BACKUP_B_ERROR_H -#define OHOS_FILEMGMT_BACKUP_B_ERROR_H - -#include -#include -#include -#include -#include -#include -#include - -#if __has_builtin(__builtin_FILE) && __has_builtin(__builtin_LINE) && __has_builtin(__builtin_FUNCTION) -#define DEFINE_SOURCE_LOCATION \ - int lineNo = __builtin_LINE(), const char *fileName = __builtin_FILE(), \ - const char *functionName = __builtin_FUNCTION() -#else -#define DEFINE_SOURCE_LOCATION int lineNo = -1, const char *fileName = "NA", const char *functionName = "NA" -#endif - -namespace OHOS::FileManagement::Backup { -class BError : public std::exception { -public: - /** - * @brief 错误码,新增错误码时需要同步补充默认错误信息 - * - */ - enum class Codes : ErrCode { - // 0 无错误 - OK = 0x0, - - // 1~999 标准平台错误 - - // 0x1000~0x1999 backup_utils错误 - UTILS_INVAL_JSON_ENTITY = 0x1000, - UTILS_INVAL_FILE_HANDLE = 0x1001, - UTILS_INVAL_TARBALL_ARG = 0x1002, - UTILS_INVAL_PROCESS_ARG = 0x1003, - UTILS_INTERRUPTED_PROCESS = 0x1004, - - // 0x2000~0x2999 backup_tool错误 - TOOL_INVAL_ARG = 0x2000, - - // 0x3000~0x3999 backup_sa错误 - SA_INVAL_ARG = 0x3000, - SA_BROKEN_IPC = 0x3001, - SA_REFUSED_ACT = 0x3002, - SA_BROKEN_ROOT_DIR = 0x3003, - - // 0x4000~0x4999 backup_SDK错误 - SDK_INVAL_ARG = 0x4000, - SDK_BROKEN_IPC = 0x4001, - SDK_MIXED_SCENARIO = 0x4002, - - // 0x5000~0x5999 backup_ext错误 - EXT_INVAL_ARG = 0x5000, - EXT_BROKEN_FRAMEWORK = 0x5001, - EXT_BROKEN_BACKUP_SA = 0x5002, - EXT_BROKEN_IPC = 0x5003, - }; - -public: - /** - * @brief 返回OHOS标准错误码 - * - * @return int 标注错误码 - */ - int GetCode() const - { - if (code_ == Codes::OK) { - return 0; - } else { - return -1 * (static_cast(code_) | ErrCodeOffset(SUBSYS_FILEMANAGEMENT, codeSubsystem_)); - } - } - - /** - * @brief 返回原始错误码 - * - * @return Codes 原始错误码 - */ - Codes GetRawCode() const - { - return code_; - } - - /** - * @brief 返回错误信息 - * - * @return const char* 错误信息 - */ - const char *what() const noexcept override - { - return msg_.c_str(); - } - - /** - * @brief 异常捕获 - * - * @param callBack 回调 - * @return ErrCode 错误码 - */ - static ErrCode ExceptionCatcherLocked(std::function callBack); - -public: - /** - * @brief 重载bool操作符,判断当前错误是否是错误 - * - * @return true 是错误 - * @return false 不是错误 - */ - explicit operator bool() const - { - return code_ != Codes::OK; - } - - /** - * @brief 返回OHOS标准错误码 - * - * @return int 标准错误码 - */ - operator int() const - { - return GetCode(); - } - -public: - /** - * @brief 构造错误对象 - * - * @param code 备份系统标准错误码,取自本类中的Codes - * @param lineNo 构造错误对象的行号(不要自己填写) - * @param fileName 构造错误对象的文件(不要自己填写) - * @param functionName 构造错误对象的函数(不要自己填写) - */ - explicit BError(Codes code = Codes::OK, DEFINE_SOURCE_LOCATION) : code_(code) - { - msg_ = WrapMessageWithExtraInfos(fileName, lineNo, functionName, code_, {mpErrToMsg_.at(code_)}); - } - - /** - * @brief 构造错误对象 - * - * @param code 备份系统标准错误码,取自本类中的Codes - * @param extraMsg 追加的详细错误信息 - * @param lineNo 构造错误对象的行号(不要自己填写) - * @param fileName 构造错误对象的文件(不要自己填写) - * @param functionName 构造错误对象的函数(不要自己填写) - */ - BError(Codes code, const std::string_view &extraMsg, DEFINE_SOURCE_LOCATION) : code_(code) - { - msg_ = WrapMessageWithExtraInfos(fileName, lineNo, functionName, code_, {mpErrToMsg_.at(code_), extraMsg}); - } - - /** - * @brief 构造错误对象 - * - * @param stdErrno 失败的LIBC调用通过errno返回的错误码 - * @param lineNo 构造错误对象的行号(不要自己填写) - * @param fileName 构造错误对象的文件(不要自己填写) - * @param functionName 构造错误对象的函数(不要自己填写) - */ - explicit BError(int stdErrno, DEFINE_SOURCE_LOCATION) : code_ {stdErrno} - { - std::string rawMsg = std::generic_category().message(stdErrno); - msg_ = WrapMessageWithExtraInfos(fileName, lineNo, functionName, code_, {rawMsg}); - } - -private: - static inline const std::map mpErrToMsg_ = { - {Codes::OK, "No error"}, - {Codes::UTILS_INVAL_JSON_ENTITY, "Json utils operated on an invalid file"}, - {Codes::UTILS_INVAL_FILE_HANDLE, "File utils received an invalid file handle"}, - {Codes::UTILS_INVAL_TARBALL_ARG, "Tarball utils received an invalid argument"}, - {Codes::UTILS_INVAL_PROCESS_ARG, "Process utils received an invalid argument"}, - {Codes::UTILS_INTERRUPTED_PROCESS, "Can't launch a process or the process was corrupted"}, - {Codes::TOOL_INVAL_ARG, "TOOL received invalid arguments"}, - {Codes::SA_INVAL_ARG, "SA received invalid arguments"}, - {Codes::SA_BROKEN_IPC, "SA failed to issue a IPC"}, - {Codes::SA_REFUSED_ACT, "SA refuse to act"}, - {Codes::SA_BROKEN_ROOT_DIR, "SA failed to operate on the given root dir"}, - {Codes::SDK_INVAL_ARG, "SDK received invalid arguments"}, - {Codes::SDK_BROKEN_IPC, "SDK failed to do IPC"}, - {Codes::SDK_MIXED_SCENARIO, "SDK involed backup/restore when doing the contrary"}, - {Codes::EXT_INVAL_ARG, "Extension received an invalid argument"}, - {Codes::EXT_BROKEN_FRAMEWORK, "Extension found the appex framework is broken"}, - {Codes::EXT_BROKEN_BACKUP_SA, "Extension found the backup SA died"}, - {Codes::EXT_BROKEN_IPC, "Extension failed to do IPC"}, - }; - -private: - const int codeSubsystem_ {1}; - Codes code_ {Codes::OK}; - std::string msg_; - -private: - /** - * @brief 生成如下格式的打印信息 → [文件名:行号->函数名] 默认错误信息. 补充错误信息 - * - * @param fileName 构造错误对象的文件 - * @param lineNo 构造错误对象的行号 - * @param functionName 构造错误对象的函数 - * @param msgs 所有待追加的错误信息 - * @return std::string 打印信息 - */ - std::string WrapMessageWithExtraInfos(const char *fileName, - int lineNo, - const char *functionName, - Codes code, - const std::vector &msgs) const; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_ERROR_H \ No newline at end of file diff --git a/utils/include/b_filesystem/b_dir.h b/utils/include/b_filesystem/b_dir.h deleted file mode 100644 index 59a641409..000000000 --- a/utils/include/b_filesystem/b_dir.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_DIR_H -#define OHOS_FILEMGMT_BACKUP_B_DIR_H - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "errors.h" - -namespace OHOS::FileManagement::Backup { -class BDir { -public: - /** - * @brief 读取指定目录下所有文件(非递归) - * - * @param 目录 - * @return 错误码、文件名数组 - */ - static std::tuple> GetDirFiles(const std::string &path); - - /** - * @brief 从给定的includes和excludes目录及文件中获取所有有用大文件和其链接文件的集合 - * - * @param includes 需要包含的文件及目录集合 - * @param excludes 需要排除的文件及目录集合 - * @return 错误码、大文件名集合 - */ - static std::pair> GetBigFiles(const std::vector &includes, - const std::vector &excludes); - -private: -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_DIR_H \ No newline at end of file diff --git a/utils/include/b_filesystem/b_file.h b/utils/include/b_filesystem/b_file.h deleted file mode 100644 index 863f4ad4b..000000000 --- a/utils/include/b_filesystem/b_file.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_FILE_H -#define OHOS_FILEMGMT_BACKUP_B_FILE_H - -#include -#include - -#include "unique_fd.h" -#include "json/json.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -class BFile { -public: - /** - * @brief 一次性读取文件全部内容 - * - * @param fd 文件描述符 - * @return std::unique_ptr 文件全部内容,保证最后一个字节为'\0' - * @throw std::system_error IO异常 - */ - static std::unique_ptr ReadFile(const UniqueFd &fd); - - /** - * @brief linux sendfile 二次封装 - * @param outFd 参数是待写入内容的文件描述符 - * @param inFd 参数是待读出内容的文件描述符 - * @throw std::system_error IO异常 - */ - static void SendFile(int outFd, int inFd); - - /** - * @brief linux write 二次封装 - * @param fd 参数是待写入内容的文件描述符 - * @param str 待写入文件的字符串 - * @throw std::system_error IO异常 - */ - static void Write(const UniqueFd &fd, const string &str); - - /** - * @brief copy file from old path to new path - * - * @param from old path - * @param to new path - * @return true copy succeess - * @return false some error occur - */ - static bool CopyFile(const string &from, const string &to); - -private: -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_FILE_H \ No newline at end of file diff --git a/utils/include/b_json/b_json_cached_entity.h b/utils/include/b_json/b_json_cached_entity.h deleted file mode 100644 index 8413c5615..000000000 --- a/utils/include/b_json/b_json_cached_entity.h +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_JSON_CACHED_ENTITY_H -#define OHOS_FILEMGMT_BACKUP_B_JSON_CACHED_ENTITY_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_filesystem/b_file.h" -#include "b_json/b_json_entity.h" -#include "filemgmt_libhilog.h" -#include "unique_fd.h" -#include "json/json.h" - -namespace OHOS::FileManagement::Backup { -template -class BJsonCachedEntity { -public: - /** - * @brief 获取结构化对象 - * - * @return T 结构化对象(即实体) - */ - T Structuralize() - { - static_assert(!std::is_default_constructible_v); - static_assert(!std::is_base_of_v); - return T(obj_); - } - - /** - * @brief 持久化JSon对象并完成 - * - * @throw std::system_error IO异常 - */ - void Persist() - { - Json::StreamWriterBuilder builder; - const std::string jsonFileContent = Json::writeString(builder, obj_); - HILOGI("Try to persist a Json object, whose content reads: %{public}s", jsonFileContent.c_str()); - - BFile::Write(srcFile_, jsonFileContent); - } - - /** - * @brief 从文件中重新加载JSon对象 - * - * @throw std::system_error IO异常或解析异常 - */ - int ReloadFromFile() - { - Json::CharReaderBuilder builder; - std::unique_ptr const jsonReader(builder.newCharReader()); - Json::Value jValue; - std::string errs; - std::unique_ptr rawBuf = BFile::ReadFile(srcFile_); - std::string_view sv(rawBuf.get()); - - if (sv.empty()) { - HILOGI("This Json file is empty"); - return 0; - } - - bool res = jsonReader->parse(sv.data(), sv.data() + sv.length(), &jValue, &errs); - if (!res || !errs.empty()) { - return BError(BError::Codes::UTILS_INVAL_JSON_ENTITY, errs).GetCode(); - } - - obj_ = std::move(jValue); - return 0; - } - - /** - * @brief 根据字符串重新加载JSon对象 - * - * @throw std::system_error IO异常或解析异常 - */ - void ReloadFromString(std::string_view sv) - { - Json::CharReaderBuilder builder; - std::unique_ptr const jsonReader(builder.newCharReader()); - Json::Value jValue; - std::string errs; - - bool res = jsonReader->parse(sv.data(), sv.data() + sv.length(), &jValue, &errs); - if (!res || !errs.empty()) { - throw BError(BError::Codes::UTILS_INVAL_JSON_ENTITY, errs); - } - - obj_ = std::move(jValue); - } - - /** - * @brief 获取JSon文件的文件描述符 - * - * @return UniqueFd& - */ - UniqueFd &GetFd() - { - return srcFile_; - } - -public: - /** - * @brief 构造方法,要求T必须具备T(Json::Value&)构造函数 - * - * @param fd 用于加载/持久化JSon对象的文件 - */ - explicit BJsonCachedEntity(UniqueFd fd) : srcFile_(std::move(fd)), entity_(std::ref(obj_)) - { - struct stat stat = {}; - if (fstat(srcFile_, &stat) == -1) { - std::stringstream ss; - ss << std::generic_category().message(errno) << " with fd eq" << srcFile_.Get(); - BError(BError::Codes::UTILS_INVAL_JSON_ENTITY, ss.str()); - return; - } - - (void)ReloadFromFile(); - } - - /** - * @brief 构造方法,要求T必须具备T(Json::Value&, std::any)构造函数 - * - * @param sv 用于加载/持久化JSon对象的字符串 - * @param option 任意类型对象 - */ - explicit BJsonCachedEntity(std::string_view sv, std::any option = std::any()) : entity_(std::ref(obj_)) - { - ReloadFromString(entity_.GetJSonSource(sv, option)); - } - -private: - UniqueFd srcFile_; - Json::Value obj_; - T entity_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_JSON_CACHED_ENTITY_H \ No newline at end of file diff --git a/utils/include/b_json/b_json_entity.h b/utils/include/b_json/b_json_entity.h deleted file mode 100644 index c3a3e1f66..000000000 --- a/utils/include/b_json/b_json_entity.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_H -#define OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_H - -#include -#include -#include - -#include "json/json.h" - -namespace OHOS::FileManagement::Backup { -class BJsonEntity { -public: - /** - * @brief 获取JSon数据源 - * - * @param jsonFromRealWorld 直接来自真实用户场景的配置文件(即,非override配置) - * @param option 任意类型对象 - * @return std::string 取决于具体情况的配置文件 - */ - std::string GetJSonSource(std::string_view jsonFromRealWorld, std::any option = std::any()) - { - return std::string(jsonFromRealWorld); - } - -public: - /** - * @brief 构造方法,具备T(Json::Value&, std::any)能力的构造函数 - * - * @param obj Json对象引用 - * @param option 任意类型对象 - */ - explicit BJsonEntity(Json::Value &obj, std::any option = std::any()) : obj_(obj), option_(option) {} - BJsonEntity() = delete; - virtual ~BJsonEntity() = default; - -protected: - Json::Value &obj_; - std::any option_; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_H \ No newline at end of file diff --git a/utils/include/b_json/b_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h deleted file mode 100644 index 7c1c7625a..000000000 --- a/utils/include/b_json/b_json_entity_caps.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_CAPS_H -#define OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_CAPS_H - -#include "b_json/b_json_cached_entity.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -class BJsonEntityCaps : public BJsonEntity { -public: - uint64_t GetFreeDiskSpace() - { - if (!obj_ || !obj_.isMember("freeDiskSpace") || !obj_["freeDiskSpace"].isUInt64()) { - HILOGE("Failed to init field FreeDiskSpace"); - return 0; - } - - return obj_["freeDiskSpace"].asUInt64(); - } - - void SetFreeDiskSpace(uint64_t freeDiskSpace) - { - obj_["freeDiskSpace"] = freeDiskSpace; - } - - void SetOSFullName(std::string osFullName) - { - obj_["OSFullName"] = osFullName; - } - - void SetDeviceType(std::string deviceType) - { - obj_["deviceType"] = deviceType; - } - - std::string GetOSFullName() - { - if (!obj_ || !obj_.isMember("OSFullName") || !obj_["OSFullName"].isString()) { - HILOGE("Failed to get field OSFullName"); - return ""; - } - - return obj_["OSFullName"].asString(); - } - - std::string GetDeviceType() - { - if (!obj_ || !obj_.isMember("deviceType") || !obj_["deviceType"].isString()) { - HILOGE("Failed to get field deviceType"); - return ""; - } - - return obj_["deviceType"].asString(); - } - -public: - /** - * @brief 构造方法,具备T(Json::Value&, std::any)能力的构造函数 - * - * @param obj Json对象引用 - * @param option 任意类型对象 - */ - explicit BJsonEntityCaps(Json::Value &obj, std::any option = std::any()) : BJsonEntity(obj, option) - { - SetFreeDiskSpace(GetFreeDiskSpace()); - } - - BJsonEntityCaps() = delete; - ~BJsonEntityCaps() override = default; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_CAPS_H \ No newline at end of file diff --git a/utils/include/b_json/b_json_entity_ext_manage.h b/utils/include/b_json/b_json_entity_ext_manage.h deleted file mode 100644 index a322a5590..000000000 --- a/utils/include/b_json/b_json_entity_ext_manage.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_EXT_MANAGE_H -#define OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_EXT_MANAGE_H - -#include -#include -#include -#include - -#include "b_json/b_json_cached_entity.h" -#include "json/json.h" - -namespace OHOS::FileManagement::Backup { -class BJsonEntityExtManage : public BJsonEntity { -public: - /** - * @brief 设置索引文件 - * - * @param info std::map> - */ - void SetExtManage(const map> &info) const; - - /** - * @brief 获取索引文件 - * - * @return std::set - */ - std::set GetExtManage() const; - - /** - * @brief 获取索引文件及详细信息 - * - * @return map> - */ - std::map> GetExtManageInfo() const; - - /** - * @brief Set the hard link Information - * - * @param origin 原始文件名 - * @param hardLinks 硬链接文件名 - * @return true 设置成功 - * @return false 设置失败 - */ - bool SetHardLinkInfo(const std::string origin, const std::set hardLinks); - - /** - * @brief Get the hard link Information - * - * @param origin 原始文件名 - * @return const 硬链接集合 - */ - const std::set GetHardLinkInfo(const string origin); - -public: - /** - * @brief 构造方法,具备T(Json::Value&, std::any)能力的构造函数 - * - * @param obj Json对象引用 - * @param option 任意类型对象 - */ - explicit BJsonEntityExtManage(Json::Value &obj, std::any option = std::any()) : BJsonEntity(obj, option) {} -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_EXT_MANAGE_H \ No newline at end of file diff --git a/utils/include/b_json/b_json_entity_extension_config.h b/utils/include/b_json/b_json_entity_extension_config.h deleted file mode 100644 index b79dd06a3..000000000 --- a/utils/include/b_json/b_json_entity_extension_config.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_EXTENSION_CONFIG_H -#define OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_EXTENSION_CONFIG_H - -#include -#include - -#include "b_json/b_json_cached_entity.h" -#include "json/json.h" - -namespace OHOS::FileManagement::Backup { -class BJsonEntityExtensionConfig : public BJsonEntity { -public: - /** - * @brief 从JSon对象中通过includes字段获取待备份目录模式串清单 - * - * @return 待备份目录模式串清单 - * @note 如果用户没有配置该字段,则返回默认打包目录{@link BConstants::PATHES_TO_BACKUP} - * @note 如果用户配置了空数组,则返回""表示生成空打包文件 - */ - std::vector GetIncludes() const; - - /** - * @brief 从JSon对象中获取排除目录列表 - * - * @return 排除目录 - */ - std::vector GetExcludes() const; - - /** - * @brief 从JSon对象中获取备份恢复权限 - * - * @return 备份权限 - */ - bool GetAllowToBackupRestore() const; - -public: - std::string GetJSonSource(std::string_view jsonFromRealWorld, std::any option); - -public: - /** - * @brief 构造方法,具备T(Json::Value&, std::any)能力的构造函数 - * - * @param obj Json对象引用 - * @param option 任意类型对象 - */ - explicit BJsonEntityExtensionConfig(Json::Value &obj, std::any option = std::any()) : BJsonEntity(obj, option) {} -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_JSON_ENTITY_EXTENSION_CONFIG_H \ No newline at end of file diff --git a/utils/include/b_ohos/startup/backup_para.h b/utils/include/b_ohos/startup/backup_para.h deleted file mode 100644 index 74d4e848a..000000000 --- a/utils/include/b_ohos/startup/backup_para.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_BACKUP_PARA_H -#define OHOS_FILEMGMT_BACKUP_BACKUP_PARA_H - -namespace OHOS::FileManagement::Backup { -class BackupPara { -public: - /** - * @brief 获取backup.para配置项backup.debug.overrideExtensionConfig的值 - * - * @return 获取的配置项backup.debug.overrideExtensionConfig值为true时则返回true,否则返回false - */ - bool GetBackupDebugOverrideExtensionConfig(); -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_BACKUP_PARA_H \ No newline at end of file diff --git a/utils/include/b_process/b_guard_cwd.h b/utils/include/b_process/b_guard_cwd.h deleted file mode 100644 index 3d352136d..000000000 --- a/utils/include/b_process/b_guard_cwd.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_GUARD_CWD_H -#define OHOS_FILEMGMT_BACKUP_B_GUARD_CWD_H - -/** - * @file b_cwd_guard.h - * @brief 异常安全的临时变更目录方法 - * - */ - -#include - -#include "nocopyable.h" - -namespace OHOS::FileManagement::Backup { -class BGuardCwd final : protected NoCopyable { -public: - /** - * @brief 构造器,其中会把当前目录变更为目标目录 - * - * @param tgtDir 目标目录 - */ - explicit BGuardCwd(std::string_view tgtDir); - - /** - * @brief 析构器,其中会把目标目录恢复为当前目录 - * - */ - ~BGuardCwd() final; - -private: - BGuardCwd() = delete; - char *pwd_ {nullptr}; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_GUARD_CWD_H \ No newline at end of file diff --git a/utils/include/b_process/b_guard_signal.h b/utils/include/b_process/b_guard_signal.h deleted file mode 100644 index 0ff4565fa..000000000 --- a/utils/include/b_process/b_guard_signal.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_GUARD_SIGNAL_H -#define OHOS_FILEMGMT_BACKUP_B_GUARD_SIGNAL_H - -/** - * @file b_guard_signal.h - * @brief 异常安全的临时调整信号处理程序方法 - * - */ - -#include - -#include "nocopyable.h" - -namespace OHOS::FileManagement::Backup { -class BGuardSignal final : protected NoCopyable { -public: - /** - * @brief 构造器,其中会把给定信号的处理程序重置为默认值 - * - * @param sig 给定信号 - */ - explicit BGuardSignal(int sig); - - /** - * @brief 析构器,其中会还原给定信号的处理程序 - * - */ - ~BGuardSignal() final; - -private: - BGuardSignal() = delete; - sighandler_t prevHandler_ {nullptr}; - int sig_ {-1}; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_GUARD_SIGNAL_H \ No newline at end of file diff --git a/utils/include/b_process/b_multiuser.h b/utils/include/b_process/b_multiuser.h deleted file mode 100644 index 02d0fbe55..000000000 --- a/utils/include/b_process/b_multiuser.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_MULTIUSER_H -#define OHOS_FILEMGMT_BACKUP_B_MULTIUSER_H - -#include "b_resources/b_constants.h" - -namespace OHOS::FileManagement::Backup { -class BMultiuser { -public: - struct UidReadOut { - int userId; - int appId; - }; - -public: - static UidReadOut ParseUid(int uid) - { - return UidReadOut { - .userId = uid / BConstants::SPAN_USERID_UID, - .appId = uid % BConstants::SPAN_USERID_UID, - }; - } -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_MULTIUSER_H \ No newline at end of file diff --git a/utils/include/b_process/b_process.h b/utils/include/b_process/b_process.h deleted file mode 100644 index c149dc18e..000000000 --- a/utils/include/b_process/b_process.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_PROCESS_H -#define OHOS_FILEMGMT_BACKUP_B_PROCESS_H - -#include -#include -#include -#include - -#include "errors.h" -#include "nocopyable.h" - -namespace OHOS::FileManagement::Backup { -class BProcess final : protected NoCopyable { -public: - /** - * @brief 执行一个命令并同步等待执行结果 - * - * @param argv 命令参数表 - * Parameter one is the command name represented by the absolute path. - * After that, parameter indicates the corresponding command parameter. - * Finally,nullptr does not need to be appended. - * - * @param DetectFatalLog 回调函数,用来对命令的stderr输出错误信息做进一步处理,检测是否发生了严重错误等。 - * - * @return 回调函数返回值,命令执行结果 - * - * @throw BError(UTILS_INVAL_PROCESS_ARG) 系统调用异常(子进程启动失败、waitpid调用失败) - * - * @throw BError(UTILS_INTERRUPTED_PROCESS) 系统调用异常(pipe调用失败、dup2调用失败、子进程被信号终止) - */ - static std::tuple ExecuteCmd(std::vector argv, - std::function DetectFatalLog = nullptr); - -private: - BProcess() = delete; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_PROCESS_H \ No newline at end of file diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h deleted file mode 100644 index d46740f55..000000000 --- a/utils/include/b_resources/b_constants.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_CONSTANTS_H -#define OHOS_FILEMGMT_BACKUP_B_CONSTANTS_H - -#include -#include -#include -#include -#include - -namespace OHOS::FileManagement::Backup::BConstants { -static inline const char *EXTENSION_ACTION_PARA = "extensionAction"; -enum class ExtensionAction { - INVALID = 0, - BACKUP = 1, - RESTORE = 2, -}; - -enum ServiceSchedAction { - WAIT = 0, - START = 1, - RUNNING = 2, - FINISH = 3, -}; - -enum EntryKey { - SUPER_LONG_PATH = 0, - SUPER_LONG_LINK_PATH, - SUPER_LONG_SIZE, -}; - -constexpr int SPAN_USERID_UID = 20000000; -constexpr int SYSTEM_UID = 0; -constexpr int DEFAULT_USER_ID = 100; -constexpr int BACKUP_UID = 1089; -constexpr int EXTENSION_THREAD_POOL_COUNT = 1; -constexpr int BACKUP_LOADSA_TIMEOUT_MS = 4000; - -constexpr int DECIMAL_BASE = 10; // 十进制基数 - -constexpr int HEADER_SIZE = 512; // 打包文件头部Header结构体大小 -constexpr int BLOCK_SIZE = 512; // 打包文件数据段尾部补充的全零字节块上限大小 -constexpr int BLOCK_PADDING_SIZE = 1024; // 打包文件尾部追加的全零字节块大小 -constexpr off_t BIG_FILE_BOUNDARY = 1024 * 1024 * 1024; // 大文件边界 -constexpr unsigned long BIG_FILE_NAME_SIZE = 16; // 大文件名长度(hash处理) - -// 打包文件头部Header结构体各字段数组/字符串大小。 -constexpr int PATHNAME_MAX_SIZE = 100; -constexpr int MODE_MAX_SIZE = 8; -constexpr int UGID_MAX_SIZE = 8; -constexpr int FILESIZE_MAX_SIZE = 12; -constexpr int TIME_MAX_SIZE = 12; -constexpr int CHKSUM_MAX_SIZE = 8; -constexpr int LINKNAME_MAX_SIZE = 100; -constexpr int MAGIC_SIZE = 6; -constexpr int VERSION_SIZE = 2; -constexpr int UGNAME_MAX_SIZE = 32; -constexpr int DEV_MAX_SIZE = 8; -constexpr int PREFIX_SIZE = 155; -constexpr int PADDING_SIZE = 12; - -// 读取backup.para字段值的最大长度 -constexpr uint32_t BACKUP_PARA_VALUE_MAX = 5; - -// SA THREAD_POOL 最大线程数 -constexpr int SA_THREAD_POOL_COUNT = 1; -// extension 最大启动数 -constexpr int EXT_CONNECT_MAX_COUNT = 3; -// SA 启动 extension 等待连接最大时间 -constexpr int EXT_CONNECT_MAX_TIME = 15000; - -// 打包文件头部Header结构体fileSize字段最大值。 -constexpr off_t FILESIZE_MAX = 077777777777; - -// 打包文件头部Header结构体typeFlag字段值。 -constexpr char TYPEFLAG_REGULAR_FILE = '0'; -constexpr char TYPEFLAG_SYMBOLIC_LINK = '2'; -constexpr char TYPEFLAG_DIRECTORY = '5'; -constexpr char TYPEFLAG_EXTENDED = 'x'; - -// 打包文件扩展数据段字段值。 -static inline std::string ENTRY_NAME_LINKPATH = "linkpath"; -static inline std::string ENTRY_NAME_PATH = "path"; -static inline std::string ENTRY_NAME_SIZE = "size"; - -// backup.para内配置项的名称,改配置项值为true时可在不更新hap包的情况下,可以读取包管理元数据配置文件的内容 -static inline std::string BACKUP_DEBUG_OVERRIDE_EXTENSION_CONFIG_KEY = "backup.debug.overrideExtensionConfig"; - -// 应用备份数据暂存路径。 -static inline std::string_view SA_BUNDLE_BACKUP_DIR = "/data/service/el2/100/backup/bundles/"; -static inline std::string_view SA_BUNDLE_BACKUP_BACKUP = "/backup/"; -static inline std::string_view SA_BUNDLE_BACKUP_RESTORE = "/restore/"; -static inline std::string_view SA_BUNDLE_BACKUP_ROOT_DIR = "/data/service/el2/100/backup/backup_sa/"; -static inline std::string_view SA_BUNDLE_BACKUP_TMP_DIR = "/tmp/"; -static inline std::string_view BACKUP_TOOL_RECEIVE_DIR = "/data/backup/received/"; -static inline std::string_view PATH_BUNDLE_BACKUP_HOME = "/data/storage/el2/backup"; -static inline std::string_view SA_BUNDLE_BACKUP_TOOL_DIR = "/data/service/el2/100/backup/backup_tool/"; -static inline std::string_view BACKUP_TOOL_LINK_DIR = "/data/backup"; - -// 备份恢复配置文件暂存路径 -static inline std::string_view BACKUP_CONFIG_EXTENSION_PATH = "/data/storage/el2/base/temp/"; - -// 应用备份恢复所需的索引文件 -static inline std::string_view EXT_BACKUP_MANAGE = "manage.json"; - -// 包管理元数据配置文件 -static inline std::string_view BACKUP_CONFIG_JSON = "backup_config.json"; - -// 应用默认备份的目录,其均为相对根路径的路径。为避免模糊匹配,务必以斜线为结尾。 -static inline std::array PATHES_TO_BACKUP = { - "data/storage/el2/database/", - "data/storage/el2/base/files/", - "data/storage/el2/base/preferences/", - "data/storage/el2/base/haps/*/database/", - "data/storage/el2/base/haps/*/base/files/", - "data/storage/el2/base/haps/*/base/preferences/", -}; -} // namespace OHOS::FileManagement::Backup::BConstants - -#endif // OHOS_FILEMGMT_BACKUP_B_CONSTANTS_H \ No newline at end of file diff --git a/utils/include/b_tarball/b_tarball_cmdline.h b/utils/include/b_tarball/b_tarball_cmdline.h deleted file mode 100644 index d00a28237..000000000 --- a/utils/include/b_tarball/b_tarball_cmdline.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_TARBALL_CMDLINE_H -#define OHOS_FILEMGMT_BACKUP_B_TARBALL_CMDLINE_H - -#include -#include -#include - -#include "nocopyable.h" - -namespace OHOS::FileManagement::Backup { -class BTarballCmdline final : protected NoCopyable { -public: - void Tar(std::string_view root, std::vector includes, std::vector excludes); - void Untar(std::string_view root); - -public: - BTarballCmdline(std::string_view tarballDir, std::string_view tarballName); - -private: - std::string tarballDir_; - std::string tarballName_; - std::string tarballPath_; -}; -} // namespace OHOS::FileManagement::Backup -#endif // OHOS_FILEMGMT_BACKUP_B_TARBALL_CMDLINE_H diff --git a/utils/include/b_tarball/b_tarball_factory.h b/utils/include/b_tarball/b_tarball_factory.h deleted file mode 100644 index 728c91c16..000000000 --- a/utils/include/b_tarball/b_tarball_factory.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_FILEMGMT_BACKUP_B_TARBALL_FACTORY_H -#define OHOS_FILEMGMT_BACKUP_B_TARBALL_FACTORY_H - -/** - * @file b_tarball.h - * @brief 使用指定实现打包/解包,本层在进行打包/解包前还负责防御路径穿越攻击 - * - */ -#include -#include -#include - -#include "nocopyable.h" - -namespace OHOS::FileManagement::Backup { -class BTarballFactory final : protected NoCopyable { -public: - /** - * @brief 打包器仿函数集合 - * 当前迫于时间所限,不得不采用命令行实现。后续必然要实现自研打包协议,从而满足在同一个进程进行打包的诉求。 - * 在降低调用成本后,就可以实现逐个向tarball追加文件的append方法。append方法是优化方法,和tar二选一即可。 - * 然而纯虚函数必须得在子类实现,这一性质使得基于继承的设计模式无法方便地选择合适的打包方法,为了解决这个问题, - * 这里采用组合的方式实现。现在在外层简单地判断相应仿函数是否为空,就知道如何进行选择了。 - */ - struct Impl { - /** - * @brief 打包 - * - * @param _1 进入该参数指定路径打包文件。 - * An absolute path is required. - * @param _2 _1中需要打包的路径。 - * 要求输入相对路径,除禁止路径穿越外无其余要求,不填默认全部打包 - * @param _3 The part that does not need to be packed in the path to be packed. - * 要求输入相对路径,路径穿越场景无实际意义因此予以禁止。可用于排除部分子目录 - */ - std::function, std::vector)> tar; - - /** - * @brief 解包 - * - * @param _1 用于存储解包文件的根目录 - * An absolute path is required. - */ - std::function untar; - }; - -public: - /** - * @brief 打包器工厂方法 - * - * @param implType 打包器实现方式,可选择'cmdline' - * @param tarballPath Absolute path of the file package。Cannot contain extra slashes, must be suffixed with .tar - * @return std::unique_ptr 打包器仿函数集合 - */ - static std::unique_ptr Create(std::string_view implType, std::string_view tarballPath); - -public: - BTarballFactory() = delete; -}; -} // namespace OHOS::FileManagement::Backup - -#endif // OHOS_FILEMGMT_BACKUP_B_TARBALL_FACTORY_H \ No newline at end of file diff --git a/utils/src/b_encryption/b_encryption.cpp b/utils/src/b_encryption/b_encryption.cpp deleted file mode 100644 index 98bad7f17..000000000 --- a/utils/src/b_encryption/b_encryption.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_encryption/b_encryption.h" - -namespace OHOS::FileManagement::Backup::BEncryption { -unsigned int CalculateChksum(const char *byteBlock, int blockSize) -{ - unsigned int chksum = 0U; - for (int i = 0; i < blockSize; ++i) { - chksum += 0xFF & *(byteBlock + i); - } - return chksum; -} -} // namespace OHOS::FileManagement::Backup::BEncryption \ No newline at end of file diff --git a/utils/src/b_error/b_error.cpp b/utils/src/b_error/b_error.cpp deleted file mode 100644 index f9745d5d8..000000000 --- a/utils/src/b_error/b_error.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_error/b_error.h" - -#include -#include - -#include "dfx_dump_catcher.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -string BError::WrapMessageWithExtraInfos(const char *fileName, - int lineNo, - const char *functionName, - Codes code, - const vector &msgs) const -{ - stringstream ss; - ss << '[' << fileName << ':' << lineNo << " -> " << functionName << ']' << ' '; - for (size_t i = 0; i < msgs.size(); ++i) { - ss << msgs[i]; - if (i != msgs.size() - 1) { - ss << ". "; - } - } - - if (code != Codes::OK) { - string msg; - HiviewDFX::DfxDumpCatcher().DumpCatch(getpid(), syscall(SYS_gettid), msg); - ss << endl << msg; - } - - string res = ss.str(); - HiviewDFX::HiLog::Error(FILEMGMT_LOG_LABEL, "%{public}s", res.c_str()); - return res; -} - -ErrCode BError::ExceptionCatcherLocked(std::function callBack) -{ - try { - return callBack(); - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGE("Unexpected exception"); - return EPERM; - } -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp deleted file mode 100644 index 3da01dbce..000000000 --- a/utils/src/b_filesystem/b_dir.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_filesystem/b_dir.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_resources/b_constants.h" -#include "directory_ex.h" -#include "errors.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -pair> GetDirFilesDetail(const string &path, bool recursion, off_t size = -1) -{ - map files; - unique_ptr> dir = {opendir(path.c_str()), closedir}; - if (!dir) { - HILOGE("Invalid directory path: %{private}s", path.c_str()); - return {BError(errno).GetCode(), files}; - } - - struct dirent *ptr = nullptr; - while (!!(ptr = readdir(dir.get()))) { - // current dir OR parent dir - if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { - continue; - } else if (ptr->d_type == DT_DIR) { - if (!recursion) { - continue; - } - - auto [errCode, subfiles] = - GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size); - if (errCode != 0) { - return {errCode, files}; - } - files.merge(subfiles); - } else if (ptr->d_type == DT_LNK) { - continue; - } else { - struct stat sta = {}; - string fileName = IncludeTrailingPathDelimiter(path) + string(ptr->d_name); - if (stat(fileName.data(), &sta) == -1) { - continue; - } - if (sta.st_size < size) { - continue; - } - HILOGI("Find big file"); - files.try_emplace(fileName, sta); - } - } - - return {BError(BError::Codes::OK).GetCode(), files}; -} - -tuple> BDir::GetDirFiles(const string &path) -{ - vector files; - unique_ptr> dir = {opendir(path.c_str()), closedir}; - if (!dir) { - HILOGE("Invalid directory path: %{private}s", path.c_str()); - return {BError(errno).GetCode(), files}; - } - - struct dirent *ptr = nullptr; - while (!!(ptr = readdir(dir.get()))) { - // current dir OR parent dir - if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { - continue; - } else if (ptr->d_type == DT_DIR) { - continue; - } else { - files.push_back(IncludeTrailingPathDelimiter(path) + string(ptr->d_name)); - } - } - - return {BError(BError::Codes::OK).GetCode(), files}; -} - -set ExpandPathWildcard(const vector &vec) -{ - unique_ptr> gl {new glob_t, [](glob_t *ptr) { globfree(ptr); }}; - *gl = {}; - - int flags = GLOB_DOOFFS | GLOB_MARK; - for (const string &pattern : vec) { - if (!pattern.empty()) { - glob(pattern.data(), flags, NULL, gl.get()); - flags |= GLOB_APPEND; - } - } - - set expandPath, filteredPath; - for (size_t i = 0; i < gl->gl_pathc; ++i) { - expandPath.emplace(gl->gl_pathv[i]); - } - - for (auto it = expandPath.begin(); it != expandPath.end(); ++it) { - filteredPath.insert(*it); - if (*it->rbegin() != '/') { - continue; - } - auto jt = it; - for (++jt; jt != expandPath.end() && (jt->find(*it) == 0); ++jt) { - } - - it = --jt; - } - - return filteredPath; -} - -pair> BDir::GetBigFiles(const vector &includes, - const vector &excludes) -{ - set inc = ExpandPathWildcard(includes); - - map incFiles; - for (const auto &item : inc) { - auto [errCode, files] = - OHOS::FileManagement::Backup::GetDirFilesDetail(item, true, BConstants::BIG_FILE_BOUNDARY); - if (errCode == 0) { - int32_t num = static_cast(files.size()); - HILOGI("found big files. total number is : %{public}d", num); - incFiles.merge(move(files)); - } - } - - auto isMatch = [](const vector &s, const string &str) -> bool { - if (str.empty()) { - return false; - } - for (const string &item : s) { - if (!item.empty() && (fnmatch(item.data(), str.data(), FNM_LEADING_DIR) == 0)) { - HILOGI("file %{public}s matchs exclude condition", str.c_str()); - return true; - } - } - return false; - }; - - map bigFiles; - for (const auto &item : incFiles) { - if (!isMatch(excludes, item.first)) { - HILOGI("file %{public}s matchs include condition and unmatchs exclude condition", item.first.c_str()); - bigFiles[item.first] = item.second; - } - } - int32_t num = static_cast(bigFiles.size()); - HILOGI("total number of big files is %{public}d", num); - return {ERR_OK, move(bigFiles)}; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_filesystem/b_file.cpp b/utils/src/b_filesystem/b_file.cpp deleted file mode 100644 index e653b32bc..000000000 --- a/utils/src/b_filesystem/b_file.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_filesystem/b_file.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -unique_ptr BFile::ReadFile(const UniqueFd &fd) -{ - if (lseek(fd, 0, SEEK_SET) == -1) { - throw BError(errno); - } - - struct stat stat = {}; - if (fstat(fd, &stat) == -1) { - throw BError(errno); - } - off_t fileSize = stat.st_size; - if (fileSize == 0) { - HILOGI("Deserialized an empty file"); - return make_unique(1); - } - - auto buf = make_unique(fileSize + 1); - if (read(fd, buf.get(), fileSize) == -1) { - throw BError(errno); - } - return buf; -} - -void BFile::SendFile(int outFd, int inFd) -{ - off_t offset = 0; - long ret = 0; - if (lseek(outFd, 0, SEEK_SET) == -1) { - throw BError(errno); - } - if (lseek(inFd, 0, SEEK_SET) == -1) { - throw BError(errno); - } - struct stat stat = {}; - if (fstat(inFd, &stat) == -1) { - throw BError(errno); - } - while ((ret = sendfile(outFd, inFd, &offset, stat.st_size)) > 0) { - }; - - if (ret == -1) { - throw BError(errno); - } -} - -void BFile::Write(const UniqueFd &fd, const string &str) -{ - int ret = pwrite(fd, str.c_str(), str.length(), 0); - if (ret == -1) { - throw BError(errno); - } - if (ftruncate(fd, ret) == -1) { - throw BError(errno); - } -} - -bool BFile::CopyFile(const string &from, const string &to) -{ - if (from == to) { - return true; - } - - try { - auto resolvedPath = make_unique(PATH_MAX); - if (!realpath(from.data(), resolvedPath.get())) { - HILOGI("failed to real path for the file %{public}s", from.c_str()); - return false; - } - string oldPath(resolvedPath.get()); - UniqueFd fdFrom(open(oldPath.data(), O_RDONLY)); - if (fdFrom == -1) { - HILOGE("failed to open the file %{public}s", from.c_str()); - throw BError(errno); - } - - unique_ptr> dir {strdup(to.data()), free}; - if (!dir) { - throw BError(errno); - } - if (!realpath(dirname(dir.get()), resolvedPath.get())) { - HILOGI("failed to real path for %{public}s", to.c_str()); - return false; - } - string newPath(resolvedPath.get()); - unique_ptr> name {strdup(to.data()), free}; - if (!name) { - throw BError(errno); - } - newPath.append("/").append(basename(name.get())); - UniqueFd fdTo(open(newPath.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); - if (fdTo == -1) { - HILOGE("failed to open the file %{public}s", to.c_str()); - throw BError(errno); - } - - SendFile(fdTo, fdFrom); - return true; - } catch (const BError &e) { - HILOGE("%{public}s", e.what()); - } catch (const exception &e) { - HILOGE("%{public}s", e.what()); - } catch (...) { - HILOGE(""); - } - return false; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_ipc/b_want_2_ext.cpp b/utils/src/b_ipc/b_want_2_ext.cpp deleted file mode 100644 index 9e34cbc91..000000000 --- a/utils/src/b_ipc/b_want_2_ext.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_ipc/b_want_2_ext.h" - -#include - -#include "b_error/b_error.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -constexpr const char *PARA_EXT_ACTION = "extensionAction"; - -void BWant2Ext::Issue() const -{ -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_json/b_json_entity_ext_manage.cpp b/utils/src/b_json/b_json_entity_ext_manage.cpp deleted file mode 100644 index 79fef1a72..000000000 --- a/utils/src/b_json/b_json_entity_ext_manage.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include "b_json/b_json_entity_ext_manage.h" -#include "filemgmt_libhilog.h" -#include "json/value.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -Json::Value Stat2JsonValue(struct stat sta) -{ - Json::Value value; - - value["st_size"] = static_cast(sta.st_size); - value["st_atim"]["tv_sec"] = static_cast(sta.st_atim.tv_sec); - value["st_atim"]["tv_nsec"] = static_cast(sta.st_atim.tv_nsec); - value["st_mtim"]["tv_sec"] = static_cast(sta.st_mtim.tv_sec); - value["st_mtim"]["tv_nsec"] = static_cast(sta.st_mtim.tv_nsec); - - return value; -} - -struct stat JsonValue2Stat(const Json::Value &value) -{ - struct stat sta = {}; - - sta.st_size = value.isMember("st_size") ? value["st_size"].asInt64() : 0; - if (value.isMember("st_atim")) { - sta.st_atim.tv_sec = value["st_atim"].isMember("tv_sec") ? value["st_atim"]["tv_sec"].asInt64() : 0; - sta.st_atim.tv_nsec = value["st_atim"].isMember("tv_nsec") ? value["st_atim"]["tv_nsec"].asInt64() : 0; - } - if (value.isMember("st_mtim")) { - sta.st_mtim.tv_sec = value["st_mtim"].isMember("tv_sec") ? value["st_mtim"]["tv_sec"].asInt64() : 0; - sta.st_mtim.tv_nsec = value["st_mtim"].isMember("tv_nsec") ? value["st_mtim"]["tv_nsec"].asInt64() : 0; - } - - return sta; -} - -void BJsonEntityExtManage::SetExtManage(const map> &info) const -{ - obj_.clear(); - - vector vec(info.size(), false); - - auto FindLinks = [&vec](map>::const_iterator it, - unsigned long index) -> set { - if (it->second.second.st_dev == 0 || it->second.second.st_ino == 0) { - return {}; - } - - set lks; - auto item = it; - item++; - - for (auto i = index + 1; i < vec.size(); ++i, ++item) { - if (it->second.second.st_dev == item->second.second.st_dev && - it->second.second.st_ino == item->second.second.st_ino) { - vec[i] = true; - lks.insert(item->second.first); - } - } - return lks; - }; - - unsigned long index = 0; - for (auto item = info.begin(); item != info.end(); ++item, ++index) { - if (vec[index]) { - HILOGI("skipped file is %{public}s", item->first.c_str()); - continue; - } - HILOGI("file name is %{public}s", item->first.c_str()); - - Json::Value value; - value["fileName"] = item->first; - value["information"]["path"] = item->second.first; - value["information"]["stat"] = Stat2JsonValue(item->second.second); - set lks = FindLinks(item, index); - for (const auto &lk : lks) { - value["hardlinks"].append(lk); - } - - obj_.append(value); - } -} - -set BJsonEntityExtManage::GetExtManage() const -{ - if (!obj_) { - HILOGE("Uninitialized JSon Object reference"); - return {}; - } - if (!obj_.isArray()) { - HILOGE("json object isn't an array"); - return {}; - } - - set info; - for (Json::Value &item : obj_) { - string fileName = item.isMember("fileName") ? item["fileName"].asString() : ""; - info.emplace(fileName); - } - return info; -} - -map> BJsonEntityExtManage::GetExtManageInfo() const -{ - if (!obj_) { - HILOGE("Uninitialized JSon Object reference"); - return {}; - } - if (!obj_.isArray()) { - HILOGE("json object isn't an array"); - return {}; - } - - map> info; - for (const Json::Value &item : obj_) { - string fileName = item.isMember("fileName") ? item["fileName"].asString() : ""; - - if (!item.isMember("information")) { - continue; - } - - struct stat sta = {}; - string path = item["information"].isMember("path") ? item["information"]["path"].asString() : ""; - if (item["information"].isMember("stat")) { - sta = JsonValue2Stat(item["information"]["stat"]); - } - - if (!fileName.empty() && !path.empty()) { - info.emplace(fileName, make_pair(path, sta)); - } - } - - return info; -} - -bool BJsonEntityExtManage::SetHardLinkInfo(const string origin, const set hardLinks) -{ - if (origin.empty()) { - HILOGE("origin file name can not empty"); - return false; - } - if (!obj_) { - HILOGE("Uninitialized JSon Object reference"); - return false; - } - if (!obj_.isArray()) { - HILOGE("json object isn't an array"); - return false; - } - - for (Json::Value &item : obj_) { - string fileName = item.isMember("fileName") ? item["fileName"].asString() : ""; - if (origin == fileName) { - for (const auto &lk : hardLinks) { - item["hardlinks"].append(lk); - } - return true; - } - } - - return false; -} - -const set BJsonEntityExtManage::GetHardLinkInfo(const string origin) -{ - if (origin.empty()) { - HILOGE("origin file name can not empty"); - return {}; - } - if (!obj_) { - HILOGE("Uninitialized JSon Object reference"); - return {}; - } - if (!obj_.isArray()) { - HILOGE("json object isn't an array"); - return {}; - } - - set hardlinks; - for (const Json::Value &item : obj_) { - string fileName = item.isMember("fileName") ? item["fileName"].asString() : ""; - if (origin == fileName) { - if (!(item.isMember("hardlinks") && item["hardlinks"].isArray())) { - break; - } - for (const auto &lk : item["hardlinks"]) { - hardlinks.emplace(lk.asString()); - } - } - } - - return hardlinks; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_json/b_json_entity_extension_config.cpp b/utils/src/b_json/b_json_entity_extension_config.cpp deleted file mode 100644 index b0c11a081..000000000 --- a/utils/src/b_json/b_json_entity_extension_config.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_json/b_json_entity_extension_config.h" - -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_filesystem/b_file.h" -#include "b_ohos/startup/backup_para.h" -#include "b_resources/b_constants.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -vector BJsonEntityExtensionConfig::GetIncludes() const -{ - if (!obj_) { - HILOGE("Uninitialized JSon Object reference"); - return {BConstants::PATHES_TO_BACKUP.begin(), BConstants::PATHES_TO_BACKUP.end()}; - } - if (!obj_.isMember("includes")) { - HILOGE("'includes' field not found"); - return {BConstants::PATHES_TO_BACKUP.begin(), BConstants::PATHES_TO_BACKUP.end()}; - } - if (!obj_["includes"].isArray()) { - HILOGE("'includes' field must be an array"); - return {BConstants::PATHES_TO_BACKUP.begin(), BConstants::PATHES_TO_BACKUP.end()}; - } - - vector dirs; - for (auto &&item : obj_["includes"]) { - if (!item.isString()) { - HILOGE("Each item of array 'includes' must be of the type string"); - continue; - } - dirs.push_back(item.asString()); - } - - if (dirs.empty()) { - dirs.emplace_back(""); - } - return dirs; -} - -vector BJsonEntityExtensionConfig::GetExcludes() const -{ - if (!obj_) { - HILOGE("Uninitialized JSon Object reference"); - return {}; - } - if (!obj_.isMember("excludes")) { - HILOGE("'excludes' field not found"); - return {}; - } - if (!obj_["excludes"].isArray()) { - HILOGE("'excludes' field must be an array"); - return {}; - } - - vector dirs; - for (auto &&item : obj_["excludes"]) { - if (!item.isString()) { - HILOGE("Each item of array 'excludes' must be of the type string"); - return {}; - } - dirs.push_back(item.asString()); - } - return dirs; -} - -bool BJsonEntityExtensionConfig::GetAllowToBackupRestore() const -{ - if (!obj_ || !obj_.isMember("allowToBackupRestore") || !obj_["allowToBackupRestore"].isBool()) { - HILOGE("Failed to init field allowToBackupRestore"); - return false; - } - - return obj_["allowToBackupRestore"].asBool(); -} - -string BJsonEntityExtensionConfig::GetJSonSource(string_view jsonFromRealWorld, any option) -{ - if (!BackupPara().GetBackupDebugOverrideExtensionConfig()) { - return string(jsonFromRealWorld); - } - - if (!option.has_value()) { - if (getuid() == static_cast(BConstants::BACKUP_UID)) { - throw BError(BError::Codes::SA_INVAL_ARG, "Current process is not extension process"); - } - string jsonFilePath = string(BConstants::BACKUP_CONFIG_EXTENSION_PATH).append(BConstants::BACKUP_CONFIG_JSON); - return BFile::ReadFile(UniqueFd(open(jsonFilePath.c_str(), O_RDONLY))).get(); - } - - if (getuid() != static_cast(BConstants::BACKUP_UID)) { - throw BError(BError::Codes::SA_INVAL_ARG, "Current process is not service process"); - } - string bundleName; - try { - bundleName = any_cast(option); - } catch (const bad_any_cast &e) { - throw BError(BError::Codes::SA_INVAL_ARG, e.what()); - } - string jsonFilePath = string(BConstants::SA_BUNDLE_BACKUP_ROOT_DIR). - append(bundleName). - append("/"). - append(BConstants::BACKUP_CONFIG_JSON); - return BFile::ReadFile(UniqueFd(open(jsonFilePath.c_str(), O_RDONLY))).get(); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_ohos/startup/backup_para.cpp b/utils/src/b_ohos/startup/backup_para.cpp deleted file mode 100644 index 2c7abcb5f..000000000 --- a/utils/src/b_ohos/startup/backup_para.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_ohos/startup/backup_para.h" - -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_resources/b_constants.h" -#include "filemgmt_libhilog.h" -#include "parameter.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -/** - * @brief 获取配置参数的值 - * - * @param key 配置参数的参数名 - * @param len 配置参数值的最大长度 - * @return 成功获取配置参数的值则返回true,失败则返回false;以及表示配置参数值的字符串 - */ -static tuple GetConfigParameterValue(const string &key, uint32_t len) -{ - int handle = static_cast(FindParameter(key.c_str())); - if (handle == -1) { - HILOGI("Fail to find parameter."); - return {false, ""}; - } - try { - unique_ptr buffer = make_unique(len + 1); - int res = GetParameterValue(handle, buffer.get(), len + 1); - if (res < 0) { - HILOGI("Fail to get parameter value."); - return {false, ""}; - } - return {true, buffer.get()}; - } catch (const bad_alloc &e) { - HILOGI("Fail to get parameter value: %{public}s.", e.what()); - return {false, ""}; - } -} - -bool BackupPara::GetBackupDebugOverrideExtensionConfig() -{ - auto [getCfgParaValSucc, value] = GetConfigParameterValue(BConstants::BACKUP_DEBUG_OVERRIDE_EXTENSION_CONFIG_KEY, - BConstants::BACKUP_PARA_VALUE_MAX); - if (!getCfgParaValSucc) { - throw BError(BError::Codes::SA_INVAL_ARG, "Fail to get configuration parameter value of backup.para"); - } - return value == "true"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_process/b_guard_cwd.cpp b/utils/src/b_process/b_guard_cwd.cpp deleted file mode 100644 index c97136ee2..000000000 --- a/utils/src/b_process/b_guard_cwd.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_process/b_guard_cwd.h" -#include "b_error/b_error.h" - -#include -#include - -namespace OHOS::FileManagement::Backup { -using namespace std; - -BGuardCwd::BGuardCwd(std::string_view tgtDir) -{ - pwd_ = getcwd(nullptr, 0); - if (!pwd_) { - throw BError(BError::Codes::UTILS_INVAL_PROCESS_ARG, "Out of memory"); - } - if (chdir(tgtDir.data())) { - std::free(pwd_); - throw BError(BError::Codes::UTILS_INVAL_PROCESS_ARG, std::generic_category().message(errno)); - } -} - -BGuardCwd::~BGuardCwd() -{ - chdir(pwd_); - free(pwd_); -} -} // namespace OHOS::FileManagement::Backup diff --git a/utils/src/b_process/b_guard_signal.cpp b/utils/src/b_process/b_guard_signal.cpp deleted file mode 100644 index 6d2c892e5..000000000 --- a/utils/src/b_process/b_guard_signal.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_process/b_guard_signal.h" - -#include - -#include "b_error/b_error.h" -#include "filemgmt_libhilog.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -BGuardSignal::BGuardSignal(int sig) : sig_(sig) -{ - prevHandler_ = signal(sig, SIG_DFL); - if (prevHandler_ == SIG_ERR) { - stringstream ss; - ss << "Invalid sigal " << sig << ", received error " << system_category().message(errno); - throw BError(BError::Codes::UTILS_INVAL_PROCESS_ARG, ss.str()); - } -} - -BGuardSignal::~BGuardSignal() -{ - if (signal(sig_, prevHandler_) == SIG_ERR) { - HILOGE("Failed to reset sig %{public}d", sig_); - } -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_process/b_process.cpp b/utils/src/b_process/b_process.cpp deleted file mode 100644 index 78b9226a2..000000000 --- a/utils/src/b_process/b_process.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_process/b_process.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_process/b_guard_signal.h" -#include "errors.h" -#include "filemgmt_libhilog.h" -#include "securec.h" -#include "unique_fd.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -static tuple WaitForChild(pid_t pid, - unique_ptr> pipeStream, - function DetectFatalLog) -{ - const int BUF_LEN = 1024; - auto buf = make_unique(BUF_LEN); - int status = 0; - - do { - regex reg("^\\W*$"); - while ((void)memset_s(buf.get(), BUF_LEN, 0, BUF_LEN), - fgets(buf.get(), BUF_LEN - 1, pipeStream.get()) != nullptr) { - if (regex_match(buf.get(), reg)) { - continue; - } - HILOGE("child process output error: %{public}s", buf.get()); - if (DetectFatalLog && DetectFatalLog(string_view(buf.get()))) { - return {true, EPERM}; - } - } - - if (waitpid(pid, &status, 0) == -1) { - throw BError(BError::Codes::UTILS_INVAL_PROCESS_ARG, generic_category().message(errno)); - } else if (WIFEXITED(status)) { - return {false, WEXITSTATUS(status)}; - } else if (WIFSIGNALED(status)) { - // 因某种信号中断获取状态 - // 异常机制存在问题,导致应用在正常的错误下Crash。为确保测试顺利展开,此处暂时屏蔽崩溃错误。 - HILOGE("some fatal errors occurred, child process is killed by a signal."); - return {true, EPERM}; - } - } while (!WIFEXITED(status) && !WIFSIGNALED(status)); - - HILOGE("If you look at me, there are some fatal errors occurred!!!"); - return {true, EPERM}; -} - -tuple BProcess::ExecuteCmd(vector argvSv, function DetectFatalLog) -{ - vector argv; - auto getStringViewData = [](const auto &arg) { return arg.data(); }; - transform(argvSv.begin(), argvSv.end(), back_inserter(argv), getStringViewData); - argv.push_back(nullptr); - - // 临时将SIGCHLD恢复成默认值,从而能够从作为僵尸进程的子进程中获得返回值 - BGuardSignal guard(SIGCHLD); - - int pipeFd[2]; - if (pipe(pipeFd) < 0) { - throw BError(BError::Codes::UTILS_INTERRUPTED_PROCESS, generic_category().message(errno)); - } - - pid_t pid = 0; - if ((pid = fork()) == 0) { - close(STDIN_FILENO); - close(STDOUT_FILENO); - close(pipeFd[0]); - UniqueFd fd(pipeFd[1]); - if (dup2(pipeFd[1], STDERR_FILENO) == -1) { - throw BError(BError::Codes::UTILS_INTERRUPTED_PROCESS, generic_category().message(errno)); - } - exit((execvp(argv[0], const_cast(argv.data())) == -1) ? errno : 0); - } - - UniqueFd fd(pipeFd[0]); - close(pipeFd[1]); - if (pid == -1) { - throw BError(BError::Codes::UTILS_INVAL_PROCESS_ARG, generic_category().message(errno)); - } - unique_ptr> pipeStream {fdopen(pipeFd[0], "r"), fclose}; - if (!pipeStream) { - throw BError(errno); - } - fd.Release(); - - return WaitForChild(pid, move(pipeStream), DetectFatalLog); -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_tarball/b_tarball_cmdline.cpp b/utils/src/b_tarball/b_tarball_cmdline.cpp deleted file mode 100644 index 521fc6e44..000000000 --- a/utils/src/b_tarball/b_tarball_cmdline.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_tarball/b_tarball_cmdline.h" - -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_process/b_guard_cwd.h" -#include "b_process/b_process.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -static bool IsTarFatalErrorOccur(string_view output) -{ - vector fatalError {"EOF", "bad xform", "bad header", "sparse overflow", - "short header", "empty archive", "Not tar"}; - for (auto &item : fatalError) { - if (output.find(item) != string_view::npos) { - return true; - } - } - return false; -} - -void BTarballCmdline::Tar(string_view root, vector includes, vector excludes) -{ - // 切换到根路径,从而在打包时使用文件或目录的相对路径 - BGuardCwd guard(root); - - vector argv = { - "/system/bin/tar", - "-cf", - tarballPath_, - }; - - if (includes.empty()) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, "tar includes argument must be not empty"); - } - - for (auto &&include : includes) { - argv.push_back(include); - } - for (auto &&exclude : excludes) { - argv.push_back("--exclude"); - argv.push_back(exclude); - } - - // 如果打包后生成了打包文件,则默认打包器打包时生成的错误可以忽略(比如打包一个不存在的文件) - auto [bFatalError, errCode] = BProcess::ExecuteCmd(argv, IsTarFatalErrorOccur); - if (bFatalError || (errCode && access(tarballPath_.data(), F_OK) != 0)) { - stringstream ss; - ss << "Is a fatal error occurred: " << bFatalError << ", error code : " << errCode; - throw BError(BError::Codes::UTILS_INVAL_PROCESS_ARG, ss.str()); - } -} - -void BTarballCmdline::Untar(string_view root) -{ - vector argv = { - "tar", "-xf", tarballPath_, "-C", root, - }; - auto [bFatalError, errCode] = BProcess::ExecuteCmd(argv, IsTarFatalErrorOccur); - if (bFatalError) { - stringstream ss; - ss << "Is a fatal error occurred in untar process: " << bFatalError << ", error code : " << errCode; - throw BError(BError::Codes::UTILS_INVAL_PROCESS_ARG, ss.str()); - } -} - -BTarballCmdline::BTarballCmdline(string_view tarballDir, string_view tarballName) - : tarballDir_(tarballDir), tarballName_(tarballName) -{ - tarballPath_ = tarballDir_ + "/" + tarballName_; -} -} // namespace OHOS::FileManagement::Backup diff --git a/utils/src/b_tarball/b_tarball_factory.cpp b/utils/src/b_tarball/b_tarball_factory.cpp deleted file mode 100644 index ddfedd8a1..000000000 --- a/utils/src/b_tarball/b_tarball_factory.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "b_tarball/b_tarball_factory.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "b_error/b_error.h" -#include "b_tarball/b_tarball_cmdline.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; - -/** - * @brief Verifying untar input parameters - * - * @param root Root directory for storing unpacked files - * An absolute path is required. - */ -static void UntarFort(string_view root) -{ - auto resolvedPath = make_unique(PATH_MAX); - if (!realpath(root.data(), resolvedPath.get()) || (string_view(resolvedPath.get()) != root)) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, "The root must be an existing canonicalized path"); - } -} - -/** - * @brief Filtering tar input parameters - * - * @param tarballDir Directory where the package file is stored - * @param root Root directory of the file to be packed - * An absolute path is required. - * @param includes Path to be packed in the root directory. - * The relative path is required. If this parameter is not specified, all packages are packed by default. - * @param excludes The part that does not need to be packed in the path to be packed - * Requires a relative path. Can be used to exclude some subdirectories - * @return std::tuple, vector> 返回合法的includes, excludes - */ -static tuple, vector> TarFilter(string_view tarballDir, - string_view root, - const vector &includes, - const vector &excludes) -{ - auto resolvedPath = make_unique(PATH_MAX); - if (!realpath(root.data(), resolvedPath.get()) || (string_view(resolvedPath.get()) != root)) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, "The root must be an existing canonicalized path"); - } - - auto removeBackSlash = [](const string_view &arg) -> string { - if (arg.empty()) { - return ""; - } - - size_t i = arg.size() - 1; - for (; i > 0; --i) { - if (arg[i] != '/') { - break; - } - } - return {arg.data(), i + 1}; - }; - - vector newExcludes; - for (auto &item : excludes) { - string str = removeBackSlash(item); - if (!str.empty()) { - newExcludes.push_back(str); - } - } - - return {{includes.begin(), includes.end()}, newExcludes}; -} - -/** - * @brief 校验tarball路径,并将之拆分为路径和文件名 - * - * @param tarballPath tarball全路径 - * @return tuple 路径和文件名 - */ -static tuple GetTarballDirAndName(string_view tarballPath) -{ - char *buf4Dir = strdup(tarballPath.data()); - if (!buf4Dir) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, "Out of memory"); - } - string tarballDir = dirname(buf4Dir); - free(buf4Dir); - - char *buf4Name = strdup(tarballPath.data()); - if (!buf4Name) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, "Out of memory"); - } - string tarballName = basename(buf4Name); - free(buf4Name); - - auto resolvedPath = make_unique(PATH_MAX); - if (!realpath(tarballDir.data(), resolvedPath.get())) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, generic_category().message(errno)); - } - if (auto canonicalizedTarballDir = string_view(resolvedPath.get()); canonicalizedTarballDir != tarballDir) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, "Tarball path differed after canonicalizing"); - } - if (auto suffix = string_view(".tar"); - tarballPath.length() <= suffix.length() || - !equal(tarballPath.rbegin(), next(tarballPath.rbegin(), suffix.length()), suffix.rbegin(), suffix.rend())) { - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, "Tarball path didn't end with '.tar'"); - } - return {tarballDir, tarballName}; -} - -/** - * @brief 绑定命令行实现的打包器 - * - * @param tarballDir taball路径 - * @param tarballName taball文件名 - * @return unique_ptr 打包器实现,包括tar和untar两种方法 - * @see GetTarballDirAndName - */ -static unique_ptr BindCmdline(string_view tarballDir, string_view tarballName) -{ - auto ptr = make_shared(tarballDir, tarballName); - - return make_unique(BTarballFactory::Impl { - .tar = bind(&BTarballCmdline::Tar, ptr, placeholders::_1, placeholders::_2, placeholders::_3), - .untar = bind(&BTarballCmdline::Untar, ptr, placeholders::_1), - }); -} - -unique_ptr BTarballFactory::Create(string_view implType, string_view tarballPath) -{ - static map(string_view, string_view)>> mapType2Tarball = { - {"cmdline", BindCmdline}, - }; - - try { - auto [tarballDir, tarballName] = GetTarballDirAndName(tarballPath); - auto tarballImpl = mapType2Tarball.at(implType)(tarballDir, tarballName); - if (tarballImpl->tar) { - tarballImpl->tar = [tarballDir {string(tarballDir)}, tar {tarballImpl->tar}]( - string_view root, vector includes, vector excludes) { - auto [newIncludes, newExcludes] = TarFilter(tarballDir, root, includes, excludes); - tar(root, {newIncludes.begin(), newIncludes.end()}, {newExcludes.begin(), newExcludes.end()}); - }; - } - if (tarballImpl->untar) { - tarballImpl->untar = [untar {tarballImpl->untar}](string_view root) { - UntarFort(root); - untar(root); - }; - } - return tarballImpl; - } catch (const out_of_range &e) { - stringstream ss; - ss << "Unsupported implementation " << implType; - throw BError(BError::Codes::UTILS_INVAL_TARBALL_ARG, ss.str()); - } -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee