diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index db8b6a930dae59e445913eb8bc9b2529a50c7e07..3a6fb94c2736f9c5442b1a82097d993a80fd71d2 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -19,6 +19,7 @@ group("innerkits_target") { "appexecfwk_base:appexecfwk_base", "appexecfwk_core:appexecfwk_core", "eventhandler_native:eventhandler_native", + "fmskit:fmskit_native", "libeventhandler:libeventhandler", "task_dispatcher:appkit_dispatcher_td", ] diff --git a/interfaces/innerkits/appexecfwk_base/BUILD.gn b/interfaces/innerkits/appexecfwk_base/BUILD.gn index 3f302de9ec7e7ef3eb0e4151b82d7c1892786b16..5f5cdaf89fe8a2170f18edd9587b0f6d1c54211b 100644 --- a/interfaces/innerkits/appexecfwk_base/BUILD.gn +++ b/interfaces/innerkits/appexecfwk_base/BUILD.gn @@ -16,7 +16,10 @@ import("//build/test.gni") import("//foundation/appexecfwk/standard/appexecfwk.gni") config("appexecfwk_base_sdk_config") { - include_dirs = [ "include" ] + include_dirs = [ + "include", + "//third_party/json/include", + ] } ohos_shared_library("appexecfwk_base") { @@ -30,9 +33,13 @@ ohos_shared_library("appexecfwk_base") { "src/compatible_application_info.cpp", "src/element_name.cpp", "src/form_info.cpp", + "src/form_js_info.cpp", + "src/form_provider_data.cpp", + "src/form_provider_info.cpp", "src/hap_module_info.cpp", "src/install_param.cpp", "src/module_info.cpp", + "src/module_usage_record.cpp", "src/permission_def.cpp", "src/running_process_info.cpp", "src/shortcut_info.cpp", diff --git a/interfaces/innerkits/appexecfwk_base/include/ability_info.h b/interfaces/innerkits/appexecfwk_base/include/ability_info.h index e452b025f8058efaac4e65ce65d681ff93174a0a..1b735140a83a651de2e67d4097187267f48b02e9 100644 --- a/interfaces/innerkits/appexecfwk_base/include/ability_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/ability_info.h @@ -148,12 +148,17 @@ struct AbilityInfo : public Parcelable { std::string label; std::string description; std::string iconPath; + int32_t labelId; + int32_t descriptionId; + int32_t iconId; std::string theme; bool visible = false; std::string kind; // ability category AbilityType type = AbilityType::UNKNOWN; DisplayOrientation orientation = DisplayOrientation::UNSPECIFIED; LaunchMode launchMode = LaunchMode::STANDARD; + std::string srcPath; + std::string srcLanguage="js"; std::vector permissions; std::string process; @@ -165,9 +170,12 @@ struct AbilityInfo : public Parcelable { bool isLauncherAbility = false; bool isNativeAbility = false; bool enabled = false; + bool supportPipMode = false; + bool formEnabled = false; std::string readPermission; std::string writePermission; - uint32_t formEntity = 1; + std::vector configChanges; + uint32_t formEntity; int32_t minFormHeight = 0; int32_t defaultFormHeight = 0; int32_t minFormWidth = 0; diff --git a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h index 6a92a32d0849186db704f1c1da7ccc6fbdcb239d..999fd70b24ddc04e578970ae08ad1152716703ea 100644 --- a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h +++ b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h @@ -24,6 +24,7 @@ enum { APPEXECFWK_MODULE_COMMON = 0x00, APPEXECFWK_MODULE_APPMGR = 0x01, APPEXECFWK_MODULE_BUNDLEMGR = 0x02, + APPEXECFWK_MODULE_FORMMGR = 0x03, APPEXECFWK_MODULE_APPEXECFWK = 0x08, // Reserved 0x03 ~ 0x0f for new modules, Event related modules start from 0x10 APPEXECFWK_MODULE_EVENTMGR = 0x10 @@ -103,6 +104,69 @@ enum { ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE, ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_MODULE }; + +// Error code for FormMgr +constexpr ErrCode APPEXECFWK_FORMMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, APPEXECFWK_MODULE_FORMMGR); +enum { + ERR_APPEXECFWK_FORM_COMMON_CODE = APPEXECFWK_FORMMGR_ERR_OFFSET + 1, + ERR_APPEXECFWK_FORM_PERMISSION_DENY, + ERR_APPEXECFWK_FORM_INTENT_PARCEL, + ERR_APPEXECFWK_FORM_GET_INFO_FAILED, + ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED, + ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, + ERR_APPEXECFWK_FORM_GET_FMS_FAILED, + ERR_APPEXECFWK_FORM_ADD_DEATH_RECIPIENT_FAILED, + ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED, + ERR_APPEXECFWK_FORM_INVALID_PARAM, + ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, + ERR_APPEXECFWK_FORM_ADD_NOT_EXIST_ID, + ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, + ERR_APPEXECFWK_FORM_EXCEED_MAX_NUMBER, + ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, + ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, + ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL, + ERR_APPEXECFWK_FORM_NO_SUCH_MODULE, + ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, + ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION, + ERR_APPEXECFWK_FORM_FA_NOT_INSTALLED, + ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, + ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, + ERR_CODE_COMMON, + ERR_NOT_EXIST_ID, + ERR_MAX_RECORDS_PER_APP, + ERR_PERMISSION_DENY, + ERR_MAX_SYSTEM_FORMS, + ERR_MAX_INSTANCES_PER_FORM, + ERR_OPERATION_FORM_NOT_SELF, + ERR_PROVIDER_DEL_FAIL, + ERR_MAX_FORMS_PER_CLIENT, + ERR_MAX_REFRESH, + ERR_MAX_SYSTEM_TEMP_FORMS, + ERR_FORM_NO_SUCH_MODULE, + ERR_FORM_NO_SUCH_ABILITY, + ERR_FORM_NO_SUCH_DIMENSION, + ERR_FORM_FA_NOT_INSTALLED, + ERR_FORM_INVALID_PARAM, + ERR_DELETE_FORM_TIMER, + ERR_CFG_NOT_MATCH_ID, + ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL, + ERR_APPEXECFWK_FORM_JSON_CREATE_DIR_FAIL, + ERR_APPEXECFWK_FORM_JSON_NEW_FILE_FAIL, + ERR_APPEXECFWK_FORM_JSON_NO_DIR, + ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL, + ERR_APPEXECFWK_FORM_JSON_FILE_EMPTY, + ERR_APPEXECFWK_FORM_JSON_FIND_FAIL, + ERR_APPEXECFWK_FORM_JSON_PARSE_FAIL, + ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, + + // error code in sdk + ERR_GET_FMS_RPC, + ERR_FORM_DUPLICATE_ADDED, + ERR_SEND_FMS_MSG, + ERR_GET_BMS_RPC, + ERR_SEND_BMS_MSG, + ERR_IN_RECOVER, +}; constexpr ErrCode APPEXECFWK_APPEXECFWK_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, APPEXECFWK_MODULE_APPEXECFWK); enum { ERR_APPEXECFWK_CHECK_FAILED = APPEXECFWK_APPEXECFWK_ERR_OFFSET + 1, @@ -111,4 +175,4 @@ enum { } // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_APPEXECFWK_ERRORS_H \ No newline at end of file +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_APPEXECFWK_ERRORS_H diff --git a/interfaces/innerkits/appexecfwk_base/include/application_info.h b/interfaces/innerkits/appexecfwk_base/include/application_info.h index 11ec2d1ae477104176d9cf9cd0a9e0ee90ffb99a..73b53e5f41e4c8022a2f927e0a42045110e9d7c5 100644 --- a/interfaces/innerkits/appexecfwk_base/include/application_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/application_info.h @@ -35,7 +35,7 @@ enum class ApplicationFlag { struct ApplicationInfo; -struct CompatibleApplicationInfo : public Parcelable { +struct CompatibleApplicationInfo : public Parcelable { // items set when installing. std::string name; // application name. std::string icon; // application icon resource index. diff --git a/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h b/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h index b809ba0d0173422e992d85c91aa79e9a4705b056..48e25adcfe14c7b43cd3a712167caa80a9113c2d 100755 --- a/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h +++ b/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h @@ -112,12 +112,17 @@ constexpr uint8_t MAX_MODULE_LABEL = 63; // distributed database const std::string APP_ID = "bundle_manager_service"; const std::string STORE_ID = "installed_bundle_datas"; +const std::string ABILITY_USAGE_STORE_ID = "ability_usage_datas"; // single max hap size constexpr int32_t MAX_HAP_SIZE = 50 * 1024 * 1024; +const std::string UID = "uid"; const int32_t MAX_LIMIT_SIZE = 4; +const std::string DATA_ABILITY_URI_PREFIX = "dataability://"; +const char DATA_ABILITY_URI_SEPARATOR = '/'; + } // namespace Constants } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/include/form_constants.h b/interfaces/innerkits/appexecfwk_base/include/form_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..0819e3111dcf3211965f4f845fecf4f921fc050e --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_constants.h @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_CONSTANTS_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_CONSTANTS_H + +#include +#include + +namespace OHOS { +namespace AppExecFwk { +namespace Constants { + const std::string PERMISSION_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; + const std::string PARAM_FORM_IDENTITY_KEY = "ohos.extra.param.key.form_identity"; + const std::string PARAM_FORM_CALLING_IDENTITY_KEY = "ohos.extra.param.key.form_calling_identity"; + const std::string PARAM_MODULE_NAME_KEY = "ohos.extra.param.key.module_name"; + const std::string PARAM_FORM_NAME_KEY = "ohos.extra.param.key.form_name"; + const std::string PARAM_FORM_DIMENSION_KEY = "ohos.extra.param.key.form_dimension"; + const std::string PARAM_MESSAGE_KEY = "ohos.extra.param.key.message"; + const std::string PARAM_FORM_TEMPORARY_KEY = "ohos.extra.param.key.form_temporary"; + const int32_t ONE_HOST_MAX_FORM_SIZE = 256; + const std::string RECREATE_FORM_KEY = "ohos.extra.param.key.recreate"; + const std::string PARAM_FORM_CUSTOMIZE_KEY = "ohos.extra.param.key.form_customize"; + const std::string PARAM_FORM_ORIENTATION_KEY = "ohos.extra.param.key.form_orientation"; + const int32_t ORIENTATION_PORTRAIT = 1; + const int32_t ORIENTATION_LANDSCAPE = 2; + const std::string PARAM_FORM_ABILITY_NAME_KEY = "abilityName"; + + const std::string KEY_IS_TIMER = "isTimerRefresh"; + const std::string SYSTEM_PARAM_FORM_UPDATE_TIME = "persist.sys.fms.form.update.time"; + const std::string SYSTEM_PARAM_FORM_REFRESH_MIN_TIME = "persist.sys.fms.form.refresh.min.time"; + const std::string ACTION_UPDATEATTIMER = "form_update_at_timer"; + const std::string KEY_WAKEUP_TIME = "wakeUpTime"; + const std::string KEY_ACTION_TYPE = "form_update_action_type"; + const int TYPE_RESET_LIMIT = 1; + const int TYPE_STATIC_UPDATE = 2; + const int TYPE_DYNAMIC_UPDATE = 3; + const long ABS_REFRESH_MS = 2500; + + // The form events type which means that the form becomes visible. + const int32_t FORM_VISIBLE = 1; + // The form events type which means that the form becomes invisible. + const int32_t FORM_INVISIBLE = 2; + + // The default user id + const int32_t DEFAULT_USER_ID = 0; + + // The max uid of system app. + const int32_t MAX_SYSTEM_APP_UID = 10000; + + const int MAX_HOUR = 23; + const int MAX_MININUTE = 59; + const int MIN_TIME = 0; + const int HOUR_PER_DAY = 24; + const int MIN_PER_HOUR = 60; + const long TIME_1000 = 1000; + const long TIME_1000000 = 1000000; + const long TIME_CONVERSION = 30 * 60 * TIME_1000; + const int MIN_CONFIG_DURATION = 1; // 1 means 30 min + const int MAX_CONFIG_DURATION = 2 * 24 * 7; // one week + const long MIN_PERIOD = MIN_CONFIG_DURATION * TIME_CONVERSION; // 30 min in ms unit + const long MAX_PERIOD = MAX_CONFIG_DURATION * TIME_CONVERSION; // 1 week in ms unit + const long ABS_TIME = 5 * TIME_1000; // 5s abs time + const int WORK_POOL_SIZE = 4; + const std::string TIME_DELIMETER = ":"; + const int UPDATE_AT_CONFIG_COUNT = 2; + + const int LIMIT_COUNT = 50; + const int MIN_NEXT_TIME = 300; // seconds + + // The max retry times of reconnection. + const int32_t MAX_RETRY_TIME = 30; + // The time interval between reconnections(milliseconds). + const int32_t SLEEP_TIME = 1000; + + const int64_t MS_PER_SECOND = 1000; + + // form host bundlename + const std::string PARAM_FORM_HOST_BUNDLENAME_KEY = "form_host_bundlename"; + + // form manager service bundlename + const std::string PARAM_FORM_MANAGER_SERVICE_BUNDLENAME_KEY = "form_manager_service_bundlename"; + + // PROVIDER_FLAG false:ProviderFormInfo is null;true: ProviderFormInfo not null + const std::string PROVIDER_FLAG = "provider_flag"; + const std::string FORM_CONNECT_ID = "form_connect_id"; + const std::string FORM_SUPPLY_INFO = "form_supply_info"; + + // the delimiter between bundleName and abilityName + const std::string NAME_DELIMITER = "::"; + + const size_t MAX_LAYOUT = 8; + const std::map DIMENSION_MAP = { + {1, "1*2"}, + {2, "2*2"}, + {3, "2*4"}, + {4, "4*4"}, + }; + const int MAX_FORMS = 512; + const int MAX_RECORD_PER_APP = 256; + const int MAX_TEMP_FORMS = 256; + const int MAX_FORM_DATA_SIZE = 1024; + + const int NOT_IN_RECOVERY = 0; + const int RECOVER_FAIL = 1; + const int IN_RECOVERING = 2; + + const int FLAG_HAS_OBJECT = 1; + const int FLAG_NO_OBJECT = 0; + + const int DEATH_RECIPIENT_FLAG = 0; + const int MAX_VISIBLE_NOTIFY_LIST = 32; + + const std::string ACQUIRE_TYPE = "form_acquire_form"; + const int ACQUIRE_TYPE_CREATE_FORM = 1; + const int ACQUIRE_TYPE_RECREATE_FORM = 2; + + const int DELETE_FORM = 3; + const int RELEASE_FORM = 8; + const int RELEASE_CACHED_FORM = 9; + + const int64_t INVALID_UDID_HASH = 0L; + + enum class FormMgrMessage { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for add form (3001) + FORM_MGR_ADD_FORM = 3001, + + // ipc id for delete form (3002) + FORM_MGR_DELETE_FORM, + + // ipc id for form done release form (3003) + FORM_MGR_RELEASE_FORM, + + // ipc id for connecting update form (3004) + FORM_MGR_UPDATE_FORM, + + // ipc id for form visible notify (3005) + FORM_MGR_NOTIFY_FORM_VISIBLE, + + // ipc id for form invisible notify (3006) + FORM_MGR_NOTIFY_FORM_INVISIBLE, + + // ipc id for refreshing data cache (3007) + FORM_MGR_CAST_TEMP_FORM, + + // ipc id 2001-3000 for tools + // ipc id for dumping state (2001) + FORM_MGR_DUMP_STATE = 2001, + }; +} // namespace Constants +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_CONSTANTS_H diff --git a/interfaces/innerkits/appexecfwk_base/include/form_death_callback.h b/interfaces/innerkits/appexecfwk_base/include/form_death_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..795d7f8f19cff4f511293e586ecc50074eb2c7b9 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_death_callback.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_DEATH_CALLBACK_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_DEATH_CALLBACK_H + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief The form death callback. + */ +class FormDeathCallback { +public: + virtual void OnDeathReceived() = 0; + virtual void OnReconnectFailed() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_DEATH_CALLBACK_H diff --git a/interfaces/innerkits/appexecfwk_base/include/form_js_info.h b/interfaces/innerkits/appexecfwk_base/include/form_js_info.h new file mode 100644 index 0000000000000000000000000000000000000000..cacddf263ddeb5e70034d4c742f02b390e6990dd --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_js_info.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H + + +#include +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @struct FormJsInfo + * Defines form js info. + */ +struct FormJsInfo : public Parcelable { + int64_t formId; + std::string formName; + std::string bundleName; + std::string abilityName; + bool formTempFlg = false; + std::string jsFormCodePath; + std::string formData; + + std::string htmlPath; + std::string cssPath; + std::string jsPath; + std::string fileReousePath; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static FormJsInfo *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h new file mode 100644 index 0000000000000000000000000000000000000000..51f2a3ef4fcb45d9b9215c4ef526aa5de65ec331 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H + +#include +#include + +#include "ashmem.h" +#include "message_parcel.h" +#include "nlohmann/json.hpp" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderData + * Defines form provider data. + */ +class FormProviderData : public Parcelable { +public: + /** + * @brief Constructor. + */ + FormProviderData(); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ + FormProviderData(nlohmann::json &jsonData); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, in JSON + * string format. + */ + FormProviderData(std::string jsonDataString); + + /** + * @brief Destructor. + */ + virtual ~FormProviderData(){}; + + /** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code nlohmann::json} format. + */ + void UpdateData(nlohmann::json &jsonData); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ + std::string GetDataString() const; + + /** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ + void AddImageData(std::string picName, char *data); + + /** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ + void RemoveImageData(std::string picName); + + /** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ + int32_t GetImageDataState(); + + /** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ + void SetImageDataState(int32_t imageDataState); + + /** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ + std::map, int32_t>> GetImageDataMap(); + + /** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ + void SetImageDataMap(std::map, int32_t>> imageDataMap); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ + nlohmann::json GetData() const; + /** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ + void SetDataString(std::string &jsonDataString); + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + /** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + /** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return Returns FormProviderData. + */ + static FormProviderData* Unmarshalling(Parcel &parcel); + + /** + * @brief Clear imageDataMap, rawImageBytesMap, imageDataState and jsonFormProviderData. + */ + void ClearData(); + +private: + bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; + +private: + nlohmann::json jsonFormProviderData_; + std::map, int32_t>> imageDataMap_; + std::map rawImageBytesMap_; + int32_t imageDataState_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H diff --git a/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h b/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h new file mode 100644 index 0000000000000000000000000000000000000000..73bfd4a478cf0b6a8c48a99b5600d4064c19f6ec --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H + +#include +#include "form_provider_data.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @struct FormProviderInfo + * Defines form provider info. + */ +class FormProviderInfo : public Parcelable { +public: + FormProviderInfo() = default; + ~FormProviderInfo() = default; + /** + * @brief Set the id of the form. + * @param formId the id of the form. + */ + inline void SetFormId(const int64_t formId) + { + formId_ = formId; + } + /** + * @brief Get the id of the form. + * @return the id of the form. + */ + inline int64_t GetFormId() const + { + return formId_; + } + /** + * @brief Set the form data. + * @param formProviderData The form data. + */ + inline void SetFormData(const FormProviderData &formProviderData) + { + jsBindingData_ = formProviderData; + } + + /** + * @brief Get the form data. + * @return the form data. + */ + inline FormProviderData GetFormData() const + { + return jsBindingData_; + } + /** + * @brief Get the form data. + * @return the form data. + */ + inline std::string GetFormDataString() const + { + return jsBindingData_.GetDataString(); + } + + /** + * @brief Set the upgrade flg. + * @param upgradeFlg The upgrade flg. + */ + inline void SetUpgradeFlg(const bool upgradeFlg) + { + upgradeFlg_ = upgradeFlg; + } + /** + * @brief Get the upgrade flg. + * @return the upgrade flg. + */ + inline bool GetUpgradeFlg() const + { + return upgradeFlg_; + } + + /** + * @brief Set form date by string. + * @param dataString string json data. + */ + void SetFormDataString(std::string &dataString); + + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static FormProviderInfo *Unmarshalling(Parcel &parcel); +private: + int64_t formId_; + FormProviderData jsBindingData_; + bool upgradeFlg_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H diff --git a/interfaces/innerkits/appexecfwk_base/include/install_param.h b/interfaces/innerkits/appexecfwk_base/include/install_param.h index fdec9375b908b96cd8898c93d6a253d0f48911b0..c389749754713580d786cc47718f94ffb7fb7e26 100644 --- a/interfaces/innerkits/appexecfwk_base/include/install_param.h +++ b/interfaces/innerkits/appexecfwk_base/include/install_param.h @@ -28,6 +28,7 @@ enum class InstallFlag { // Allow to replace the existing bundle when the new version isn't lower than the old one. // If the bundle does not exist, just like normal flag. REPLACE_EXISTING = 1, + FREE_INSTALL = 0x10, }; enum class InstallLocation { @@ -42,6 +43,7 @@ struct InstallParam : public Parcelable { int userId = 0; // is keep user data while uninstall. bool isKeepData = false; + bool noCheckSignature = false; // the parcel object function is not const. bool ReadFromParcel(Parcel &parcel); diff --git a/interfaces/innerkits/appexecfwk_base/include/launcher_ability_info.h b/interfaces/innerkits/appexecfwk_base/include/launcher_ability_info.h new file mode 100644 index 0000000000000000000000000000000000000000..33fa0eee279be6bcb146792b42949071e3475b41 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/launcher_ability_info.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_ABILITYINFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_ABILITYINFO_H + +#include + +#include "application_info.h" +#include "element_name.h" + +namespace OHOS { +namespace AppExecFwk { + +struct LauncherAbilityInfo { +public: + std::string name; // ability name, only the main class name + ApplicationInfo applicationInfo; + std::string label; + ElementName elementname; + std::string icon; + int32_t userid; + int64_t installTime; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_ABILITYINFO_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/include/launcher_shortcut_info.h b/interfaces/innerkits/appexecfwk_base/include/launcher_shortcut_info.h new file mode 100644 index 0000000000000000000000000000000000000000..825b4a123f7fef7ed98a42a1ace2e2744ac9392f --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/launcher_shortcut_info.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_SHORTCUT_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_SHORTCUT_INFO_H + +#include "shortcut_info.h" + +namespace OHOS { +namespace AppExecFwk { + +struct LauncherShortcutInfo { + std::string icon; + std::vector intents; + std::string shortcutid; + std::string bundleName; + std::string label; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_SHORTCUT_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/include/module_usage_record.h b/interfaces/innerkits/appexecfwk_base/include/module_usage_record.h new file mode 100644 index 0000000000000000000000000000000000000000..faf211f237de308dc28bde2d3dbf8ba9d06764ee --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/module_usage_record.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_MODULE_USAGE_RECORD_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_MODULE_USAGE_RECORD_H + +#include + +#include "ability_info.h" +#include "parcel.h" +#include "refbase.h" + +namespace OHOS { +namespace AppExecFwk { +namespace UsageRecordKey { + const std::string LAUNCHED_COUNT = "launchedCount"; + const std::string LAST_LAUNCH_TIME = "lastLaunchTime"; + const std::string IS_REMOVED = "isRemoved"; + const std::string ABILITY_NAME = "abilityName"; + const std::string SCHEMA_LAST_LAUNCH_TIME = "$.lastLaunchTime"; +} // UsageRecordKey + +struct ModuleUsageRecord : public Parcelable { + std::string bundleName; + uint32_t appLabelId = 0; + std::string name; + uint32_t labelId = 0; + uint32_t descriptionId = 0; + std::string abilityName; + uint32_t abilityLabelId = 0; + uint32_t abilityDescriptionId = 0; + uint32_t abilityIconId = 0; + uint32_t launchedCount = 0; + int64_t lastLaunchTime = 0; + bool removed = false; + bool installationFreeSupported = true; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ModuleUsageRecord *Unmarshalling(Parcel &parcel); + std::string ToString() const; + bool FromJsonString(const std::string &jsonString); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_MODULE_USAGE_RECORD_H diff --git a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp index 33497a8851eae9561aaa57cf828a26a3c91b3f23..f3b64dcefd215b819d650385707c52cb036acc5f 100644 --- a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp @@ -58,9 +58,11 @@ const std::string JSON_KEY_DEVICE_ID = "deviceId"; const std::string JSON_KEY_IS_LAUNCHER_ABILITY = "isLauncherAbility"; const std::string JSON_KEY_IS_NATIVE_ABILITY = "isNativeAbility"; const std::string JSON_KEY_ENABLED = "enabled"; +const std::string JSON_KEY_SUPPORT_PIP_MODE = "supportPipMode"; const std::string JSON_KEY_TARGET_ABILITY = "targetAbility"; const std::string JSON_KEY_READ_PERMISSION = "readPermission"; const std::string JSON_KEY_WRITE_PERMISSION = "writePermission"; +const std::string JSON_KEY_CONFIG_CHANGES = "configChanges"; const std::string JSON_KEY_FORM = "form"; const std::string JSON_KEY_FORM_ENTITY = "formEntity"; const std::string JSON_KEY_MIN_FORM_HEIGHT = "minFormHeight"; @@ -73,6 +75,10 @@ const std::string JSON_KEY_CUSTOMIZE_DATA = "customizeData"; const std::string JSON_KEY_META_DATA = "metaData"; const std::string JSON_KEY_META_VALUE = "value"; const std::string JSON_KEY_META_EXTRA = "extra"; +const std::string JSON_KEY_LABEL_ID = "labelId"; +const std::string JSON_KEY_DESCRIPTION_ID = "descriptionId"; +const std::string JSON_KEY_ICON_ID = "iconId"; +const std::string JSON_KEY_FORM_ENABLED = "formEnabled"; } // namespace @@ -101,12 +107,21 @@ bool AbilityInfo::ReadFromParcel(Parcel &parcel) isLauncherAbility = parcel.ReadBool(); isNativeAbility = parcel.ReadBool(); enabled = parcel.ReadBool(); - + supportPipMode = parcel.ReadBool(); + formEnabled = parcel.ReadBool(); + int32_t configChangesSize; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, configChangesSize); + for (int32_t i = 0; i < configChangesSize; i++) { + configChanges.emplace_back(Str16ToStr8(parcel.ReadString16())); + } formEntity = parcel.ReadInt32(); minFormHeight = parcel.ReadInt32(); defaultFormHeight = parcel.ReadInt32(); minFormWidth = parcel.ReadInt32(); defaultFormWidth = parcel.ReadInt32(); + labelId = parcel.ReadInt32(); + descriptionId = parcel.ReadInt32(); + iconId = parcel.ReadInt32(); int32_t typeData; READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, typeData); @@ -222,11 +237,20 @@ bool AbilityInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isLauncherAbility); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isNativeAbility); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, enabled); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, supportPipMode); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, formEnabled); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, configChanges.size()); + for (auto &configChange : configChanges) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(configChange)); + } WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, formEntity); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, minFormHeight); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, defaultFormHeight); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, minFormWidth); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, defaultFormWidth); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, labelId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, descriptionId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, iconId); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(type)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(orientation)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(launchMode)); @@ -286,8 +310,9 @@ void AbilityInfo::Dump(std::string prefix, int fd) APP_LOGE("dump Abilityinfo fcntl error %{public}s", strerror(errno)); return; } - flags &= O_ACCMODE; - if ((flags == O_WRONLY) || (flags == O_RDWR)) { + uint uflags = static_cast(flags); + uflags &= O_ACCMODE; + if ((uflags == O_WRONLY) || (uflags == O_RDWR)) { nlohmann::json jsonObject = *this; std::string result; result.append(prefix); @@ -347,13 +372,18 @@ void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo) {JSON_KEY_IS_LAUNCHER_ABILITY, abilityInfo.isLauncherAbility}, {JSON_KEY_IS_NATIVE_ABILITY, abilityInfo.isNativeAbility}, {JSON_KEY_ENABLED, abilityInfo.enabled}, + {JSON_KEY_SUPPORT_PIP_MODE, abilityInfo.supportPipMode}, {JSON_KEY_READ_PERMISSION, abilityInfo.readPermission}, {JSON_KEY_WRITE_PERMISSION, abilityInfo.writePermission}, + {JSON_KEY_CONFIG_CHANGES, abilityInfo.configChanges}, {JSON_KEY_FORM_ENTITY, abilityInfo.formEntity}, {JSON_KEY_MIN_FORM_HEIGHT, abilityInfo.minFormHeight}, {JSON_KEY_DEFAULT_FORM_HEIGHT, abilityInfo.defaultFormHeight}, {JSON_KEY_MIN_FORM_WIDTH, abilityInfo.minFormWidth}, {JSON_KEY_DEFAULT_FORM_WIDTH, abilityInfo.defaultFormWidth}, + {JSON_KEY_LABEL_ID, abilityInfo.labelId}, + {JSON_KEY_DESCRIPTION_ID, abilityInfo.descriptionId}, + {JSON_KEY_ICON_ID, abilityInfo.iconId}, {JSON_KEY_KIND, abilityInfo.kind}, {JSON_KEY_TYPE, abilityInfo.type}, {JSON_KEY_ORIENTATION, abilityInfo.orientation}, @@ -372,7 +402,8 @@ void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo) {JSON_KEY_CODE_PATH, abilityInfo.codePath}, {JSON_KEY_RESOURCE_PATH, abilityInfo.resourcePath}, {JSON_KEY_LIB_PATH, abilityInfo.libPath}, - {JSON_KEY_META_DATA, abilityInfo.metaData} + {JSON_KEY_META_DATA, abilityInfo.metaData}, + {JSON_KEY_FORM_ENABLED, abilityInfo.formEnabled} }; } @@ -415,13 +446,18 @@ void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo) abilityInfo.isLauncherAbility = jsonObject.at(JSON_KEY_IS_LAUNCHER_ABILITY).get(); abilityInfo.isNativeAbility = jsonObject.at(JSON_KEY_IS_NATIVE_ABILITY).get(); abilityInfo.enabled = jsonObject.at(JSON_KEY_ENABLED).get(); + abilityInfo.supportPipMode = jsonObject.at(JSON_KEY_SUPPORT_PIP_MODE).get(); abilityInfo.readPermission = jsonObject.at(JSON_KEY_READ_PERMISSION).get(); abilityInfo.writePermission = jsonObject.at(JSON_KEY_WRITE_PERMISSION).get(); + abilityInfo.configChanges = jsonObject.at(JSON_KEY_CONFIG_CHANGES).get>(); abilityInfo.formEntity = jsonObject.at(JSON_KEY_FORM_ENTITY).get(); abilityInfo.minFormHeight = jsonObject.at(JSON_KEY_MIN_FORM_HEIGHT).get(); abilityInfo.defaultFormHeight = jsonObject.at(JSON_KEY_DEFAULT_FORM_HEIGHT).get(); abilityInfo.minFormWidth = jsonObject.at(JSON_KEY_MIN_FORM_WIDTH).get(); abilityInfo.defaultFormWidth = jsonObject.at(JSON_KEY_DEFAULT_FORM_WIDTH).get(); + abilityInfo.labelId = jsonObject.at(JSON_KEY_LABEL_ID).get(); + abilityInfo.descriptionId = jsonObject.at(JSON_KEY_DESCRIPTION_ID).get(); + abilityInfo.iconId = jsonObject.at(JSON_KEY_ICON_ID).get(); abilityInfo.kind = jsonObject.at(JSON_KEY_KIND).get(); abilityInfo.type = jsonObject.at(JSON_KEY_TYPE).get(); abilityInfo.orientation = jsonObject.at(JSON_KEY_ORIENTATION).get(); @@ -441,6 +477,7 @@ void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo) abilityInfo.resourcePath = jsonObject.at(JSON_KEY_RESOURCE_PATH).get(); abilityInfo.libPath = jsonObject.at(JSON_KEY_LIB_PATH).get(); abilityInfo.metaData = jsonObject.at(JSON_KEY_META_DATA).get(); + abilityInfo.formEnabled = jsonObject.at(JSON_KEY_FORM_ENABLED).get(); } void AbilityInfo::ConvertToCompatiableAbilityInfo(CompatibleAbilityInfo& compatibleAbilityInfo) const @@ -462,6 +499,7 @@ void AbilityInfo::ConvertToCompatiableAbilityInfo(CompatibleAbilityInfo& compati compatibleAbilityInfo.permissions = permissions; compatibleAbilityInfo.deviceTypes = deviceTypes; compatibleAbilityInfo.deviceCapabilities = deviceCapabilities; + compatibleAbilityInfo.supportPipMode = supportPipMode; compatibleAbilityInfo.readPermission = readPermission; compatibleAbilityInfo.writePermission = writePermission; compatibleAbilityInfo.bundleName = bundleName; @@ -474,6 +512,9 @@ void AbilityInfo::ConvertToCompatiableAbilityInfo(CompatibleAbilityInfo& compati compatibleAbilityInfo.defaultFormHeight = defaultFormHeight; compatibleAbilityInfo.minFormWidth = minFormWidth; compatibleAbilityInfo.defaultFormWidth = defaultFormWidth; + compatibleAbilityInfo.iconId = iconId; + compatibleAbilityInfo.labelId = labelId; + compatibleAbilityInfo.descriptionId = descriptionId; compatibleAbilityInfo.enabled = enabled; } diff --git a/interfaces/innerkits/appexecfwk_base/src/application_info.cpp b/interfaces/innerkits/appexecfwk_base/src/application_info.cpp index 7fc357a4e76e2f83a9355d150def9b7a69e9f9b6..8ae6e966e8f6fddc0b8dd1515894fbda66a2641c 100644 --- a/interfaces/innerkits/appexecfwk_base/src/application_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/application_info.cpp @@ -142,8 +142,9 @@ void ApplicationInfo::Dump(std::string prefix, int fd) APP_LOGE("dump ApplicationInfo fcntl error %{public}s", strerror(errno)); return; } - flags &= O_ACCMODE; - if ((flags == O_WRONLY) || (flags == O_RDWR)) { + uint uflags = static_cast(flags); + uflags &= O_ACCMODE; + if ((uflags == O_WRONLY) || (uflags == O_RDWR)) { nlohmann::json jsonObject = *this; std::string result; result.append(prefix); @@ -216,17 +217,22 @@ void from_json(const nlohmann::json &jsonObject, ApplicationInfo &applicationInf void ApplicationInfo::ConvertToCompatibleApplicationInfo(CompatibleApplicationInfo& compatibleApplicationInfo) const { + APP_LOGD("ApplicationInfo::ConvertToCompatibleApplicationInfo called"); compatibleApplicationInfo.name = name; + //compatibleApplicationInfo.icon = icon; compatibleApplicationInfo.label = label; compatibleApplicationInfo.description = description; + //compatibleApplicationInfo.cpuAbi = cpuAbi; compatibleApplicationInfo.process = process; compatibleApplicationInfo.systemApp = isSystemApp; + //compatibleApplicationInfo.isCompressNativeLibs = isCompressNativeLibs; compatibleApplicationInfo.iconId = iconId; compatibleApplicationInfo.labelId = labelId; compatibleApplicationInfo.descriptionId = descriptionId; compatibleApplicationInfo.permissions = permissions; compatibleApplicationInfo.moduleInfos = moduleInfos; compatibleApplicationInfo.supportedModes = supportedModes; + //compatibleApplicationInfo.enabled = debug; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/appexecfwk_base/src/compatible_ability_info.cpp b/interfaces/innerkits/appexecfwk_base/src/compatible_ability_info.cpp index e6253fa5ddcf124b38e7682db1c1e51b1a018fe3..80092620a71f8fd655cc1c7e751eb6f04d684e4f 100644 --- a/interfaces/innerkits/appexecfwk_base/src/compatible_ability_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/compatible_ability_info.cpp @@ -63,6 +63,51 @@ bool CompatibleAbilityInfo::ReadFromParcel(Parcel& parcel) READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, launchModeData); launchMode = static_cast(launchModeData); + // int32_t permissionsSize; + // READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, permissionsSize); + // if (permissionsSize > Constants::MAX_LIMIT_SIZE) { + // APP_LOGE("permissions size is overflow"); + // return false; + // } + // for (int32_t i = 0; i < permissionsSize; i++) { + // std::string permission = Str16ToStr8(parcel.ReadString16()); + // if (permission.empty()) { + // APP_LOGE("ReadParcelable failed"); + // return false; + // } + // permissions.emplace_back(permission); + // } + + // int32_t deviceTypeSize; + // READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, deviceTypeSize); + // if (deviceTypeSize > Constants::MAX_DEVICETYPE_SIZE) { + // APP_LOGE("device type size is overflow"); + // return false; + // } + // for (auto i = 0; i < deviceTypeSize; i++) { + // std::string deviceType = Str16ToStr8(parcel.ReadString16()); + // if (deviceType.empty()) { + // APP_LOGE("ReadParcelable failed"); + // return false; + // } + // deviceTypes.emplace_back(deviceType); + // } + + // int32_t deviceCapabilitySize; + // READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, deviceCapabilitySize); + // if (deviceCapabilitySize > Constants::MAX_LIMIT_SIZE) { + // APP_LOGE("device capability size is overflow"); + // return false; + // } + // for (auto i = 0; i < deviceCapabilitySize; i++) { + // std::string deviceCapability = Str16ToStr8(parcel.ReadString16()); + // if (deviceCapability.empty()) { + // APP_LOGE("ReadParcelable failed"); + // return false; + // } + // deviceCapabilities.emplace_back(deviceCapability); + // } + supportPipMode = parcel.ReadBool(); grantPermission = parcel.ReadBool(); readPermission = Str16ToStr8(parcel.ReadString16()); @@ -73,6 +118,12 @@ bool CompatibleAbilityInfo::ReadFromParcel(Parcel& parcel) bundleName = Str16ToStr8(parcel.ReadString16()); className = Str16ToStr8(parcel.ReadString16()); deviceId = Str16ToStr8(parcel.ReadString16()); + // std::unique_ptr appInfo(parcel.ReadParcelable()); + // if (!appInfo) { + // APP_LOGE("ReadParcelable failed"); + // return false; + // } + // applicationInfo = *appInfo; formEntity = parcel.ReadInt32(); minFormHeight = parcel.ReadInt32(); defaultFormHeight = parcel.ReadInt32(); @@ -124,6 +175,27 @@ bool CompatibleAbilityInfo::Marshalling(Parcel& parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(orientation)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(launchMode)); + // for compatible with JAVA. + // const auto permissionsSize = static_cast(permissions.size()); + // WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, permissionsSize); + // for (auto i = 0; i < permissionsSize; i++) { + // WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(permissions[i])); + // } + + // // for compatible with JAVA. + // const auto deviceTypeSize = static_cast(deviceTypes.size()); + // WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, deviceTypeSize); + // for (auto i = 0; i < deviceTypeSize; i++) { + // WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(deviceTypes[i])); + // } + + // // for compatible with JAVA. + // const auto deviceCapabilitySize = static_cast(deviceCapabilities.size()); + // WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, deviceCapabilitySize); + // for (auto i = 0; i < deviceCapabilitySize; i++) { + // WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(deviceCapabilities[i])); + // } + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, supportPipMode); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, grantPermission); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(readPermission)); @@ -135,6 +207,9 @@ bool CompatibleAbilityInfo::Marshalling(Parcel& parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(className)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(deviceId)); APP_LOGE("CompatibleAbilityInfo::Marshalling start to write application info."); + // if (!parcel.WriteParcelable(&applicationInfo)) { + // return false; + // } WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, formEntity); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, minFormHeight); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, defaultFormHeight); @@ -166,6 +241,7 @@ void CompatibleAbilityInfo::ConvertToAbilityInfo(AbilityInfo& abilityInfo) const abilityInfo.permissions = permissions; abilityInfo.deviceTypes = deviceTypes; abilityInfo.deviceCapabilities = deviceCapabilities; + abilityInfo.supportPipMode = supportPipMode; abilityInfo.readPermission = readPermission; abilityInfo.writePermission = writePermission; abilityInfo.bundleName = bundleName; @@ -178,6 +254,9 @@ void CompatibleAbilityInfo::ConvertToAbilityInfo(AbilityInfo& abilityInfo) const abilityInfo.defaultFormHeight = defaultFormHeight; abilityInfo.minFormWidth = minFormWidth; abilityInfo.defaultFormWidth = defaultFormWidth; + abilityInfo.iconId = iconId; + abilityInfo.labelId = labelId; + abilityInfo.descriptionId = descriptionId; abilityInfo.enabled = enabled; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/appexecfwk_base/src/compatible_application_info.cpp b/interfaces/innerkits/appexecfwk_base/src/compatible_application_info.cpp index ec8bab48224fb0c99ff6a13a834615e3edcfe162..8c1ddf82ae02c48bcb7f9d9734f8a1fd15d7555f 100644 --- a/interfaces/innerkits/appexecfwk_base/src/compatible_application_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/compatible_application_info.cpp @@ -17,8 +17,8 @@ #include #include -#include -#include +#include +#include #include "nlohmann/json.hpp" #include "string_ex.h" @@ -137,10 +137,13 @@ void CompatibleApplicationInfo::ConvertToApplicationInfo(ApplicationInfo& applic { APP_LOGD("CompatibleApplicationInfo::ConvertToApplicationInfo called"); applicationInfo.name = name; + //applicationInfo.icon = icon; applicationInfo.label = label; applicationInfo.description = description; + //applicationInfo.cpuAbi = cpuAbi; applicationInfo.process = process; applicationInfo.isSystemApp = systemApp; + //applicationInfo.isCompressNativeLibs = isCompressNativeLibs; applicationInfo.iconId = iconId; applicationInfo.labelId = labelId; applicationInfo.descriptionId = descriptionId; @@ -148,6 +151,7 @@ void CompatibleApplicationInfo::ConvertToApplicationInfo(ApplicationInfo& applic applicationInfo.moduleInfos = moduleInfos; applicationInfo.supportedModes = supportedModes; applicationInfo.enabled = debug; + //applicationInfo.entryModuleName = ""; } } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b674f42bd2d18ab6fc7ad7ae21f9971ce87ba1b --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 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 "form_js_info.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool FormJsInfo::ReadFromParcel(Parcel &parcel) +{ + formId = parcel.ReadInt64(); + formName = Str16ToStr8(parcel.ReadString16()); + bundleName = Str16ToStr8(parcel.ReadString16()); + abilityName = Str16ToStr8(parcel.ReadString16()); + + formTempFlg = parcel.ReadBool(); + jsFormCodePath = Str16ToStr8(parcel.ReadString16()); + formData = Str16ToStr8(parcel.ReadString16()); + + return true; +} + +FormJsInfo *FormJsInfo::Unmarshalling(Parcel &parcel) +{ + FormJsInfo *formJsInfo = new (std::nothrow) FormJsInfo(); + if (formJsInfo && !formJsInfo->ReadFromParcel(parcel)) { + delete formJsInfo; + formJsInfo = nullptr; + } + return formJsInfo; +} + +bool FormJsInfo::Marshalling(Parcel &parcel) const +{ + // write formId + if (!parcel.WriteInt64(formId)) { + return false; + } + // write formName + if (!parcel.WriteString16(Str8ToStr16(formName))) { + return false; + } + // write bundleName + if (!parcel.WriteString16(Str8ToStr16(bundleName))) { + return false; + } + // write abilityName + if (!parcel.WriteString16(Str8ToStr16(abilityName))) { + return false; + } + + // write tempFlag + if (!parcel.WriteBool(formTempFlg)) { + return false; + } + + // write jsFormCodePath + if (!parcel.WriteString16(Str8ToStr16(jsFormCodePath))) { + return false; + } + + // write formData + if (!parcel.WriteString16(Str8ToStr16(formData))) { + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e314d468e144efc2d81f3895e5c8874507c0fd7b --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_provider_data.h" +#include "message_parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +const int IMAGE_DATA_STATE_REMOVED = -1; +const int IMAGE_DATA_STATE_NO_OPERATION = 0; +const int IMAGE_DATA_STATE_ADDED = 1; + +/** + * @brief Constructor. + */ +FormProviderData::FormProviderData() +{ + jsonFormProviderData_.clear(); +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ +FormProviderData::FormProviderData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, + * in JSON string format. + */ +FormProviderData::FormProviderData(std::string jsonDataString) +{ + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} + +/** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code ZSONObject} format. + */ +void FormProviderData::UpdateData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ +nlohmann::json FormProviderData::GetData() const +{ + return jsonFormProviderData_; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ +std::string FormProviderData::GetDataString() const +{ + APP_LOGI("%{public}s called", __func__); + return jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); +} + +/** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ +void FormProviderData::AddImageData(std::string picName, char *data) +{ + if ((picName.length() == 0) || (sizeof(data) == 0)) { + APP_LOGE("input param is NULL!"); + return; + } + + rawImageBytesMap_[picName] = data; + + imageDataState_ = IMAGE_DATA_STATE_ADDED; +} + +/** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ +void FormProviderData::RemoveImageData(std::string picName) +{ + rawImageBytesMap_.erase(picName); +} + +/** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ +void FormProviderData::SetDataString(std::string &jsonDataString) +{ + APP_LOGI("%{public}s called", __func__); + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} +/** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ +void FormProviderData::MergeData(nlohmann::json &addJsonData) +{ + APP_LOGI("%{public}s called", __func__); + if (addJsonData.empty()) { + return; + } + + if (jsonFormProviderData_.empty()) { + jsonFormProviderData_ = addJsonData; + return; + } + + for (auto &it : addJsonData.items()) { + jsonFormProviderData_[it.key()] = it.value(); + } +} + +/** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ +std::map, int32_t>> FormProviderData::GetImageDataMap() +{ + return imageDataMap_; +} + +/** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ +int32_t FormProviderData::GetImageDataState() +{ + return imageDataState_; +} + +/** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ +void FormProviderData::SetImageDataState(int32_t imageDataState) +{ + imageDataState_ = imageDataState; +} + +/** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ +void FormProviderData::SetImageDataMap(std::map, int32_t>> imageDataMap) +{ + imageDataMap_ = imageDataMap; +} + +/** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::ReadFromParcel(Parcel &parcel) +{ + jsonFormProviderData_ = nlohmann::json::parse(Str16ToStr8(parcel.ReadString16())); + // MessageParcel* messageParcel = dynamic_cast&parcel; // dynamic_cast need rtti + // if(messageParcel == nullptr) { + // return true; + // } + + imageDataState_ = parcel.ReadInt32(); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + int32_t imageDataNum = parcel.ReadInt32(); + for (int32_t i = 0; i < imageDataNum; i++) { + MessageParcel* messageParcel = (MessageParcel*)&parcel; + sptr ashmem = messageParcel->ReadAshmem(); + if (ashmem == nullptr) { + APP_LOGE("%{public}s failed, ashmem is nullptr", __func__); + return false; + } + + int32_t len = parcel.ReadInt32(); + std::pair, int32_t> imageDataRecord = std::make_pair(ashmem, len); + imageDataMap_.emplace(Str16ToStr8(parcel.ReadString16()), imageDataRecord); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::Marshalling(Parcel &parcel) const +{ + APP_LOGI("%{public}s called", __func__); + if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump()))) { + return false; + } + // MessageParcel* messageParcel = dynamic_cast&parcel; // dynamic_cast need rtti + // if(messageParcel == nullptr) { + // return true; + // } + + parcel.WriteInt32(imageDataState_); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + if (rawImageBytesMap_.size() == 0) { + APP_LOGE("%{public}s failed, rawImageBytesMap_ is empty", __func__); + return false; + } + parcel.WriteInt32(rawImageBytesMap_.size()); // firstly write the number of shared image to add + for (auto &entry : rawImageBytesMap_) { + if (!WriteImageDataToParcel(parcel, entry.first, entry.second)) { + APP_LOGE("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); + return false; + } + parcel.WriteInt32(sizeof(entry.second)); + parcel.WriteString16(Str8ToStr16(entry.first)); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return FormProviderData. + */ +FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) +{ + FormProviderData *formProviderData = new (std::nothrow) FormProviderData(); + if (formProviderData && !formProviderData->ReadFromParcel(parcel)) { + delete formProviderData; + formProviderData = nullptr; + } + + return formProviderData; +} + +/** + * @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_. + */ +void FormProviderData::ClearData() +{ + jsonFormProviderData_.clear(); +} + +bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const +{ + sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), sizeof(data)); + if (ashmem == nullptr) { + APP_LOGE("create shared memory fail"); + return false; + } + + bool ret = ashmem->MapReadAndWriteAshmem(); + if (!ret) { + APP_LOGE("map shared memory fail"); + return false; + } + + ret = ashmem->WriteToAshmem(data, sizeof(data), 0); + if (!ret) { + APP_LOGE("write image data to shared memory fail"); + return false; + } + + ashmem->UnmapAshmem(); + + MessageParcel* messageParcel = (MessageParcel*)&parcel; + ret = messageParcel->WriteAshmem(ashmem); + + ashmem->CloseAshmem(); // close ashmem after writeAshmem because writeAshmem will dup fd + if (!ret) { + APP_LOGE("writeAshmem fail, the picture name is %{public}s", picName.c_str()); + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64773c9d5afdbb863b9ed57dddfaaaf6290691e6 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 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 "form_provider_info.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool FormProviderInfo::ReadFromParcel(Parcel &parcel) +{ + formId_ = parcel.ReadInt64(); + auto bindingData = parcel.ReadParcelable(); + jsBindingData_ = *bindingData; + return true; +} + +FormProviderInfo *FormProviderInfo::Unmarshalling(Parcel &parcel) +{ + FormProviderInfo *formProviderInfo = new (std::nothrow) FormProviderInfo(); + if (formProviderInfo && !formProviderInfo->ReadFromParcel(parcel)) { + delete formProviderInfo; + formProviderInfo = nullptr; + } + return formProviderInfo; +} + +bool FormProviderInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt64(formId_)) { + return false; + } + if (!parcel.WriteParcelable(&jsBindingData_)) { + return false; + } + + return true; +} +void FormProviderInfo::SetFormDataString(std::string &dataString) +{ + jsBindingData_.SetDataString(dataString); +} +/** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ +void FormProviderInfo::MergeData(nlohmann::json &addJsonData) +{ + jsBindingData_.MergeData(addJsonData); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/install_param.cpp b/interfaces/innerkits/appexecfwk_base/src/install_param.cpp index 378233ae391c89b379a11914c1f4e9aba3ab0b0a..639c79683cd849d79e7453b509c8d9af10f23461 100644 --- a/interfaces/innerkits/appexecfwk_base/src/install_param.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/install_param.cpp @@ -36,6 +36,7 @@ bool InstallParam::ReadFromParcel(Parcel &parcel) userId = parcel.ReadInt32(); isKeepData = parcel.ReadBool(); + noCheckSignature = parcel.ReadBool(); return true; } @@ -56,6 +57,7 @@ bool InstallParam::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(installLocation)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, userId); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isKeepData); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, noCheckSignature); return true; } diff --git a/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp b/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..369f47976ab59af6c8775c75d394d72244b0a601 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 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_usage_record.h" + +#include "string_ex.h" + +#include "app_log_wrapper.h" +#include "nlohmann/json.hpp" +#include "parcel_macro.h" + +namespace OHOS { +namespace AppExecFwk { + +bool ModuleUsageRecord::ReadFromParcel(Parcel &parcel) +{ + name = Str16ToStr8(parcel.ReadString16()); + bundleName = Str16ToStr8(parcel.ReadString16()); + abilityName = Str16ToStr8(parcel.ReadString16()); + appLabelId = parcel.ReadInt32(); + labelId = parcel.ReadInt32(); + descriptionId = parcel.ReadInt32(); + abilityLabelId = parcel.ReadInt32(); + abilityDescriptionId = parcel.ReadInt32(); + abilityIconId = parcel.ReadInt32(); + launchedCount = parcel.ReadInt32(); + lastLaunchTime = parcel.ReadInt64(); + removed = parcel.ReadBool(); + installationFreeSupported = parcel.ReadBool(); + return true; +} + +ModuleUsageRecord *ModuleUsageRecord::Unmarshalling(Parcel &parcel) +{ + ModuleUsageRecord *record = new ModuleUsageRecord(); + if (!record->ReadFromParcel(parcel)) { + APP_LOGW("read ModuleUsageRecord from parcel failed"); + delete record; + record = nullptr; + } + return record; +} + +bool ModuleUsageRecord::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(name)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(bundleName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(abilityName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, appLabelId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, labelId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, descriptionId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, abilityLabelId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, abilityDescriptionId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, abilityIconId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, launchedCount); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int64, parcel, lastLaunchTime); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, removed); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, installationFreeSupported); + return true; +} + +std::string ModuleUsageRecord::ToString() const +{ + nlohmann::json json; + json[UsageRecordKey::LAUNCHED_COUNT] = launchedCount; + json[UsageRecordKey::LAST_LAUNCH_TIME] = lastLaunchTime; + json[UsageRecordKey::IS_REMOVED] = removed; + json[UsageRecordKey::ABILITY_NAME] = abilityName; + return json.dump(); +} + +bool ModuleUsageRecord::FromJsonString(const std::string &jsonString) +{ + nlohmann::json jsonObject; + + jsonObject = nlohmann::json::parse(jsonString); + if (jsonObject.is_discarded()) { + APP_LOGE("failed to parse module usage record: %{public}s.", jsonString.c_str()); + return false; + } + this->launchedCount = jsonObject.at(UsageRecordKey::LAUNCHED_COUNT).get(); + this->lastLaunchTime = jsonObject.at(UsageRecordKey::LAST_LAUNCH_TIME).get(); + this->removed = jsonObject.at(UsageRecordKey::IS_REMOVED).get(); + this->abilityName = jsonObject.at(UsageRecordKey::ABILITY_NAME).get(); + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/BUILD.gn b/interfaces/innerkits/appexecfwk_core/BUILD.gn index e42c15b90fbdc089b7f5d32f7aeae9c44febdf6b..476fbe715326bfbda56e497e06962c3ef284e669 100644 --- a/interfaces/innerkits/appexecfwk_core/BUILD.gn +++ b/interfaces/innerkits/appexecfwk_core/BUILD.gn @@ -18,6 +18,7 @@ config("appmgr_sdk_config") { include_dirs = [ "include/appmgr", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", ] } @@ -25,6 +26,10 @@ config("bundlemgr_sdk_config") { include_dirs = [ "include/bundlemgr" ] } +config("formmgr_sdk_config") { + include_dirs = [ "include/formmgr" ] +} + config("appexecfwk_core_config") { include_dirs = [ "include" ] } @@ -34,6 +39,7 @@ ohos_shared_library("appexecfwk_core") { "//third_party/json/include", "${services_path}/appmgr/include", "${services_path}/bundlemgr/include", + "${services_path}/formmgr/include", "//utils/system/safwk/native/include", ] @@ -59,20 +65,33 @@ ohos_shared_library("appexecfwk_core") { "src/bundlemgr/bundle_installer_proxy.cpp", "src/bundlemgr/bundle_mgr_host.cpp", "src/bundlemgr/bundle_mgr_proxy.cpp", + "src/bundlemgr/bundle_monitor.cpp", "src/bundlemgr/bundle_status_callback_host.cpp", "src/bundlemgr/bundle_status_callback_proxy.cpp", "src/bundlemgr/clean_cache_callback_host.cpp", "src/bundlemgr/clean_cache_callback_proxy.cpp", + "src/bundlemgr/launcher_service.cpp", "src/bundlemgr/on_permission_changed_callback_host.cpp", "src/bundlemgr/on_permission_changed_callback_proxy.cpp", "src/bundlemgr/status_receiver_host.cpp", "src/bundlemgr/status_receiver_proxy.cpp", + "src/formmgr/form_host_proxy.cpp", + "src/formmgr/form_host_stub.cpp", + "src/formmgr/form_mgr_proxy.cpp", + "src/formmgr/form_mgr_stub.cpp", + "src/formmgr/form_provider_proxy.cpp", + "src/formmgr/form_provider_stub.cpp", + "src/formmgr/form_supply_proxy.cpp", + "src/formmgr/form_supply_stub.cpp", + "src/formmgr/provider_connect_proxy.cpp", + "src/formmgr/provider_connect_stub.cpp", ] public_configs = [ ":appexecfwk_core_config", ":appmgr_sdk_config", ":bundlemgr_sdk_config", + ":formmgr_sdk_config", ] defines = [ @@ -93,6 +112,9 @@ ohos_shared_library("appexecfwk_core") { ] external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni b/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni index a0bae2802bbe6e8a02c091fe58222e758f8b01a0..0be383b054db52dc24ad0fe8d8e6a53318e9b699 100644 --- a/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni +++ b/interfaces/innerkits/appexecfwk_core/appexecfwk_headers.gni @@ -24,6 +24,10 @@ appexecfwk_headers = { "bundlemgr/status_receiver_interface.h", "bundlemgr/on_permission_changed_callback_interface.h", "appmgr/app_process_data.h", + "formmgr/form_mgr_interface.h", + "formmgr/form_host_interface.h", + "formmgr/form_provider_interface.h", + "formmgr/form_supply_interface.h", ] header_base = "interfaces/innerkits/appexecfwk_core/include" diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_process_data.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_process_data.h index 8ba81a3d45294d64ae08099b21e59c1ee267533e..aae4d474947e44df12d1f1f0045e8d9d9df2b109 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_process_data.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_process_data.h @@ -52,6 +52,7 @@ struct AppProcessData : public Parcelable { std::string processName; ApplicationState appState = ApplicationState::APP_STATE_CREATE; pid_t pid = 0; + int32_t uid = 0; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_host.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_host.h index cae86ca55d2dc4572da77a3b845a94ed56e393c5..ecf6aff158e0dc47f42a537b364ef360764c0cdd 100644 --- a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_host.h +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_host.h @@ -118,6 +118,13 @@ private: * @return Returns ERR_OK if called successfully; returns error code otherwise. */ ErrCode HandleQueryAbilityInfo(Parcel &data, Parcel &reply); + /** + * @brief Handles the QueryAbilityInfos function called from a IBundleMgr proxy object. + * @param data Indicates the data to be read. + * @param reply Indicates the reply to be sent; + * @return Returns ERR_OK if called successfully; returns error code otherwise. + */ + ErrCode HandleQueryAbilityInfos(Parcel &data, Parcel &reply); /** * @brief Handles the QueryAbilityInfoByUri function called from a IBundleMgr proxy object. * @param data Indicates the data to be read. @@ -370,7 +377,20 @@ private: * @return Returns ERR_OK if called successfully; returns error code otherwise. */ ErrCode HandleGetShortcutInfos(Parcel &data, Parcel &reply); - + /** + * @brief Handles the HandleGetModuleUsageRecords function called from a IBundleMgr proxy object. + * @param data Indicates the data to be read. + * @param reply Indicates the reply to be sent; + * @return Returns ERR_OK if called successfully; returns error code otherwise. + */ + ErrCode HandleGetModuleUsageRecords(Parcel &data, Parcel &reply); + /** + * @brief Handles the HandleNotifyActivityLifeStatus function called from a IBundleMgr proxy object. + * @param data Indicates the data to be read. + * @param reply Indicates the reply to be sent; + * @return Returns ERR_OK if called successfully; returns error code otherwise. + */ + ErrCode HandleNotifyActivityLifeStatus(Parcel &data, Parcel &reply); private: /** * @brief Write a parcelabe vector objects to the proxy node. diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h index ce84212199c336b6dd7cf9f84d8aa9d81727d113..ea34e91cfad88e80c9c9231789fb28251f22ef63 100644 --- a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_interface.h @@ -19,6 +19,7 @@ #include "ability_info.h" #include "form_info.h" #include "shortcut_info.h" +#include "module_usage_record.h" #include "application_info.h" #include "bundle_info.h" #include "hap_module_info.h" @@ -147,6 +148,13 @@ public: * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. */ virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) = 0; + /** + * @brief Query the AbilityInfo of list by the given Want. + * @param want Indicates the information of the ability. + * @param abilityInfos Indicates the obtained AbilityInfos object. + * @return Returns true if the AbilityInfos is successfully obtained; returns false otherwise. + */ + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) = 0; /** * @brief Query the AbilityInfo by ability.uri in config.json. * @param abilityUri Indicates the uri of the ability. @@ -391,11 +399,27 @@ public: * @return Returns true if this function is successfully called; returns false otherwise. */ virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) = 0; + /** + * @brief Get module usage record list in descending order of lastLaunchTime. + * @param maxNum the return size of the records, must be in range of 1 to 1000. + * @param moduleUsageRecords List of ModuleUsageRecord objects if obtained. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) = 0; /** * @brief Obtains the interface used to install and uninstall bundles. * @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise. */ virtual sptr GetBundleInstaller() = 0; + /** + * @brief Notify a specified ability for activity. + * @param bundleName Indicates the bundle name of the ability to activity. + * @param abilityName Indicates the name of the ability to activity. + * @param launchTime Indicates the ability launchTime. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) = 0; enum class Message { GET_APPLICATION_INFO, @@ -412,6 +436,7 @@ public: CHECK_IS_SYSTEM_APP_BY_UID, GET_BUNDLE_INFOS_BY_METADATA, QUERY_ABILITY_INFO, + QUERY_ABILITY_INFOS, QUERY_ABILITY_INFO_BY_URI, QUERY_KEEPALIVE_BUNDLE_INFOS, GET_ABILITY_LABEL, @@ -445,8 +470,10 @@ public: GET_ALL_FORMS_INFO, GET_FORMS_INFO_BY_APP, GET_FORMS_INFO_BY_MODULE, - GET_SHORTCUT_INFO, + GET_MODULE_USAGE_RECORD, + GET_SHORTCUT_INFO, GET_BUNDLE_INSTALLER, + NOTIFY_ACTIVITY_LIFE_STATUS, }; }; diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h index 82d74f9831b8008bb670d5fd9effaf9e0a7aeadb..bd268e69f4c1fd2877d7e17291fde1fad86d9d30 100644 --- a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h @@ -136,6 +136,13 @@ public: * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. */ virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) override; + /** + * @brief Query the AbilityInfo of list by the given Want. + * @param want Indicates the information of the ability. + * @param abilityInfos Indicates the obtained AbilityInfos object. + * @return Returns true if the AbilityInfos is successfully obtained; returns false otherwise. + */ + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override; /** * @brief Query the AbilityInfo by ability.uri in config.json through the proxy object. * @param abilityUri Indicates the uri of the ability. @@ -387,6 +394,23 @@ public: * @return Returns true if this function is successfully called; returns false otherwise. */ virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) override; + /** + * @brief Get module usage record list in descending order of lastLaunchTime. + * @param maxNum the return size of the records, must be in range of 1 to 1000. + * @param moduleUsageRecords List of ModuleUsageRecord objects if obtained. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) override; + /** + * @brief Notify a specified ability for activity. + * @param bundleName Indicates the bundle name of the ability to activity. + * @param abilityName Indicates the name of the ability to activity. + * @param launchTime Indicates the ability launchTime. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override; + private: /** * @brief Send a command message from the proxy object. diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_monitor.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..337502c15bd92726df633dda2ebd5021179486e8 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_monitor.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_MONITOR_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_MONITOR_H + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "bundle_status_callback_interface.h" +#include "bundle_constants.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +class BundleMonitor : public EventFwk::CommonEventSubscriber, public std::enable_shared_from_this { +public: + using Want = OHOS::AAFwk::Want; + + BundleMonitor(const EventFwk::CommonEventSubscribeInfo &subscribeInfo); + ~BundleMonitor() = default; + + /** + * @brief Subscribe commonEvent. + * @param callback The callback of IBundleStatusCallback + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool Subscribe(const sptr &callback); + /** + * @brief Unsubscribe commonEvent. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UnSubscribe(); + /** + * @brief CommonEvent callback. + * @param eventData publish common event data. + * @return + */ + void OnReceiveEvent(const EventFwk::CommonEventData &eventData); + +private: + const std::string BUNDLE_NAME = "bundleName"; + const std::string USER_ID = "userId"; + sptr callback_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_MONITOR_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h index 7764cff7cbb6391f044a86a89a8dc3010157816f..e498c616a46f55cc094e497968922d3f24c000a9 100644 --- a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_interface.h @@ -41,6 +41,24 @@ public: */ virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) = 0; + /** + * @brief Called when a new application package has been installed on the device. + * @param bundleName Indicates the name of the bundle whose state has been installed. + * @param userId Indicates the id of the bundle whose state has been installed. + */ + virtual void OnBundleAdded(const std::string &bundleName, const int userId) = 0; + /** + * @brief Called when a new application package has been Updated on the device. + * @param bundleName Indicates the name of the bundle whose state has been Updated. + * @param userId Indicates the id of the bundle whose state has been Updated. + */ + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) = 0; + /** + * @brief Called when a new application package has been Removed on the device. + * @param bundleName Indicates the name of the bundle whose state has been Removed. + * @param userId Indicates the id of the bundle whose state has been Removed. + */ + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) = 0; enum class Message { ON_BUNDLE_STATE_CHANGED, diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_proxy.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_proxy.h index ad8a0dedc913d3e1c3ab849e0c66f6db9661b4de..1ff2832b4a5bafd1005cde6dd9529495b242e280 100644 --- a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/bundle_status_callback_proxy.h @@ -39,6 +39,24 @@ public: */ virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) override; + /** + * @brief Called when a new application package has been installed on the device. + * @param bundleName Indicates the name of the bundle whose state has been installed. + * @param userId Indicates the id of the bundle whose state has been installed. + */ + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override {}; + /** + * @brief Called when a new application package has been Updated on the device. + * @param bundleName Indicates the name of the bundle whose state has been Updated. + * @param userId Indicates the id of the bundle whose state has been Updated. + */ + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override {}; + /** + * @brief Called when a new application package has been Removed on the device. + * @param bundleName Indicates the name of the bundle whose state has been Removed. + * @param userId Indicates the id of the bundle whose state has been Removed. + */ + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override {}; private: static inline BrokerDelegator delegator_; diff --git a/interfaces/innerkits/appexecfwk_core/include/bundlemgr/launcher_service.h b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/launcher_service.h new file mode 100644 index 0000000000000000000000000000000000000000..83ba113d6f89a368972e00d5bea09035c98300ce --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/bundlemgr/launcher_service.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_SERVICE_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_SERVICE_H + +#include +#include + +#include "bundle_mgr_interface.h" +#include "securec.h" +#include "system_ability_definition.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "bundle_monitor.h" +#include "bundle_status_callback_interface.h" +#include "launcher_ability_info.h" +#include "launcher_shortcut_info.h" +#include "ability_info.h" +#include "application_info.h" +#include "want.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +class LauncherService { +public: + using Want = OHOS::AAFwk::Want; + + LauncherService(); + virtual ~LauncherService() = default; + + /** + * @brief Registers a callback method for monitoring bundle installation, uninstallation, and update events. + * @param callback Indicates the callback method to be called. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool RegisterCallback(const sptr &callback); + /** + * @brief Unregisters the callback method for monitoring bundle installation, uninstallation, and update events. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool UnRegisterCallback(); + /** + * @brief Obtains launcher abilities based on the bundle name and user id. + * @param bundleName Indicates the bundle name. + * @param userId Indicates the user ID. + * @param launcherAbilityInfos List of LauncherAbilityInfo objects if obtained; + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetAbilityList( + const std::string &bundleName, const int userId, std::vector &launcherAbilityInfos); + /** + * @brief Obtains launcher ability based on the want and user id. + * @param want Indicates the application bundle name to be queried. + * @param userId Indicates the user ID. + * @param launcherAbilityInfo Indicates the obtained LauncherAbilityInfo object. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetAbilityInfo(const Want &want, const int userId, LauncherAbilityInfo &launcherAbilityInfo); + /** + * @brief Obtains the ApplicationInfo based on a given bundle name. + * @param bundleName Indicates the application bundle name to be queried. + * @param flag Indicates the flag used to specify information contained + * in the ApplicationInfo object that will be returned. + * @param userId Indicates the user ID. + * @param applicationInfo Indicates the obtained ApplicationInfo object. + * @return Returns true if the function is successfully called; returns false otherwise. + */ + virtual bool GetApplicationInfo(const std::string &bundleName, const ApplicationFlag &flags, const int userId, + ApplicationInfo &applicationInfo); + /** + * @brief Checks whether a bundle exists and is enabled. + * @param bundleName Indicates the bundle name. + * @return Returns true if the bundle is enabled; returns false otherwise. + */ + virtual bool IsBundleEnabled(const std::string &bundleName); + /** + * @brief Checks whether an ability exists and is enabled. + * @param abilityInfo Indicates information about the ability to check. + * @return Returns true if the ability exists and is enabled; returns false otherwise. + */ + virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo); + /** + * @brief Obtains information about the shortcuts of the application. + * @param bundleName Indicates the bundle name of the application. + * @param launcherShortcutInfo List of LauncherShortcutInfo objects if obtained. + * @return Returns true if the function is successfully called; returns false otherwise. + */ + virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &launcherShortcutInfo); + +private: + void init(); + OHOS::sptr GetBundleMgr(); + + std::shared_ptr bundleMonitor_ = nullptr; + + DISALLOW_COPY_AND_MOVE(LauncherService); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_LAUNCHER_SERVICE_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_interface.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..07812871c50cf471347cc3b146757ac794b147b5 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_interface.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_INTERFACE_H + +#include + +#include "form_js_info.h" +#include "ipc_types.h" +#include "iremote_broker.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class IFormHost + * IFormHost interface is used to access form host service. + */ +class IFormHost : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormHost"); + + /** + * @brief Request to give back a Form. + * @param formInfo Form info. + */ + virtual void OnAcquired(const FormJsInfo &formInfo) = 0; + + /** + * @brief Form is updated. + * @param formInfo Form info. + */ + virtual void OnUpdate(const FormJsInfo &formInfo) = 0; + + /** + * @brief Form provider is uninstalled. + * @param formIds The Id list of the forms. + */ + virtual void OnUninstall(const std::vector &formIds) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for create (3001) + FORM_HOST_ON_ACQUIRED = 3681, + + // ipc id for update (3682) + FORM_HOST_ON_UPDATE, + + // ipc id for uninstall (3683) + FORM_HOST_ON_UNINSTALL, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_INTERFACE_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_proxy.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..255fa5d39e76e303dec31e2aad2a6a97ed21ea7a --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_proxy.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_PROXY_H + +#include "app_log_wrapper.h" +#include "form_host_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostProxy + * Form host proxy is used to access form host service. + */ +class FormHostProxy : public IRemoteProxy { +public: + explicit FormHostProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormHostProxy() = default; + + /** + * @brief Request to give back a Form. + * @param formInfo Form info. + */ + virtual void OnAcquired(const FormJsInfo &formInfo) override; + + /** + * @brief Form is updated. + * @param formInfo Form info. + */ + virtual void OnUpdate(const FormJsInfo &formInfo) override; + + /** + * @brief Form provider is uninstalled. + * @param formIds The Id list of the forms. + */ + virtual void OnUninstall(const std::vector &formIds) override; + +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_PROXY_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_stub.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..1c32be18be7194a8d3c98913e80327d4ad81047d --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_host_stub.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_STUB_H + +#include + +#include "form_host_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostStub + * Form host service stub. + */ +class FormHostStub : public IRemoteStub { +public: + FormHostStub(); + virtual ~FormHostStub(); + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief handle OnAcquired message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleAcquired(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle OnUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnUpdate(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle OnUnInstall message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnUninstall(MessageParcel &data, MessageParcel &reply); +private: + using FormHostFunc = int32_t (FormHostStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormHostStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_HOST_STUB_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_interface.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..19b3d58e7d6b966a77fa02961a22dded1c91c706 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_interface.h @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_INTERFACE_H + +#include +#include "form_js_info.h" +#include "form_provider_data.h" +#include "ipc_types.h" +#include "iremote_broker.h" + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; + +/** + * @class IFormMgr + * IFormMgr interface is used to access form manager service. + */ +class IFormMgr : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormMgr") + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo) = 0; + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DeleteForm(const int64_t formId, const sptr &callerToken) = 0; + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) = 0; + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const std::string &bundleName, + const FormProviderData &formProviderData) = 0; + + /** + * @brief Set next refresh time. + * @param formId The Id of the form to update. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetNextRefreshTime(const int64_t formId, const int64_t nextTime) = 0; + + /** + * @brief Lifecycle update. + * @param formIds The Id of the forms. + * @param callerToken Caller ability token. + * @param updateType update type. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType) = 0; + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to request. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) = 0; + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType) = 0; + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CastTempForm(const int64_t formId, const sptr &callerToken) = 0; + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpStorageFormInfos(std::string &formInfos) = 0; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) = 0; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) = 0; + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + virtual int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for create (3001) + FORM_MGR_ADD_FORM = 3001, + FORM_MGR_ADD_FORM_OHOS, + FORM_MGR_DELETE_FORM, + FORM_MGR_UPDATE_FORM, + FORM_MGR_LIFECYCLE_UPDATE, + FORM_MGR_REQUEST_FORM, + FORM_MGR_RELEASE_FORM, + FORM_MGR_RELEASE_CACHED_FORM, + FORM_MGR_CAST_TEMP_FORM, + FORM_MGR_EVENT_NOTIFY, + FORM_MGR_CHECK_AND_DELETE_INVALID_FORMS, + FORM_MGR_SET_NEXT_REFRESH_TIME, + FORM_MGR_ACQUIRE_FORM_STATE, + FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE, + FORM_MGR_STORAGE_FORM_INFOS, + FORM_MGR_FORM_INFOS_BY_NAME, + FORM_MGR_FORM_INFOS_BY_ID, + FORM_MGR_MESSAGE_EVENT, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_INTERFACE_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_proxy.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..576f077c005f0b1975faf508cb74e8a1b91a0668 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_proxy.h @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_PROXY_H + +#include "form_mgr_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormMgrProxy + * FormMgrProxy is used to access form manager service. + */ +class FormMgrProxy : public IRemoteProxy { +public: + explicit FormMgrProxy(const sptr &impl); + virtual ~FormMgrProxy() = default; + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo) override; + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DeleteForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) override; + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param FormProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const std::string &bundleName, + const FormProviderData &FormProviderData) override; + + /** + * @brief Set next refresh time. + * @param formId The Id of the form to update. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int SetNextRefreshTime(const int64_t formId, const int64_t nextTime) override; + + /** + * @brief Lifecycle update. + * @param formIds The Id of the forms. + * @param callerToken Caller ability token. + * @param updateType update type. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType) override; + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) override; + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType) override; + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CastTempForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpStorageFormInfos(std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) override; + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + virtual int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) override; +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + template + int GetParcelableInfo(IFormMgr::Message code, MessageParcel &data, T &parcelableInfo); + int SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply); + int GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo); +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_PROXY_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_stub.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..95467215c8c891b8c921b8a8428a9c4c495f724d --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_mgr_stub.h @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_STUB_H + +#include + +#include "form_mgr_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormMgrStub + * Form manager service stub. + */ +class FormMgrStub : public IRemoteStub { +public: + FormMgrStub(); + virtual ~FormMgrStub(); + /** + * @brief Handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief Handle AddForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleAddForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DeleteForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDeleteForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle ReleaseForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleReleaseForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle UpdateForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleUpdateForm(MessageParcel &data, MessageParcel &reply); + + /** + * @brief handle LifecycleUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleLifecycleUpdate(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle SetNextRefreshTime message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleSetNextRefreshTime(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle RequestForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleRequestForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle NotifyWhetherVisibleForms message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleNotifyWhetherVisibleForms(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle CastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleCastTempForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpStorageFormInfos message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDumpStorageFormInfos(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpFormInfoByBundleName message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDumpFormInfoByBundleName(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleDumpFormInfoByFormId(MessageParcel &data, MessageParcel &reply); + /** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t HandleMessageEvent(MessageParcel &data, MessageParcel &reply); + +private: + using FormMgrFunc = int32_t (FormMgrStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormMgrStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_MGR_STUB_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_interface.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..425ad1673f3c3a2309feac69dfacb47ec63b4b7f --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_interface.h @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_INTERFACE_H + +#include + +#include "ipc_types.h" +#include "iremote_broker.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; +/** + * @class IFormProvider + * IFormProvider interface is used to access form provider service. + */ +class IFormProvider : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormProvider"); + + /** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the from. + * @param want Indicates the {@link Want} structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) = 0; + + /** + * @brief Notify provider when the form was deleted. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormDelete(const int64_t formId, const Want &want, const sptr &callerToken) = 0; + + /** + * @brief Notify provider when the forms was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) = 0; + /** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &callerToken) = 0; + + /** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) = 0; + + /** + * @brief Notify provider when the temp form was cast to normal form. + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) = 0; + + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for add form (3001) + FORM_ACQUIRE_PROVIDER_FORM_INFO = 3051, + + // ipc id for delete form (3052) + FORM_PROVIDER_NOTIFY_FORM_DELETE, + + // ipc id for form done release form (3053) + FORM_PROVIDER_NOTIFY_FORMS_DELETE, + + // ipc id for connecting update form (3054) + FORM_PROVIDER_NOTIFY_FORM_UPDATE, + + // ipc id for form visible notify (3055) + FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST, + + // ipc id for event notify (3056) + FORM_PROVIDER_EVENT_NOTIFY, + + // ipc id for event notify (3057) + FORM_PROVIDER_EVENT_MESSAGE, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_INTERFACE_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_proxy.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..4344d59b58041f6d1b71a9a9a83da1db9c020ea1 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_proxy.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_PROXY_H + +#include "app_log_wrapper.h" +#include "form_provider_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderProxy + * FormProviderProxy is used to access form provider service. + */ +class FormProviderProxy : public IRemoteProxy { +public: + explicit FormProviderProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormProviderProxy() = default; + + /** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the from. + * @param want Indicates the {@link Want} structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form was deleted. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormDelete(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the forms was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormUpdate(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) override; + + /** + * @brief Notify provider when the temp form was cast to normal form. + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) override; + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) override; + +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_PROXY_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_stub.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..5c0751e96dbce5622ac43682238143346b68ccad --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_provider_stub.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_STUB_H + +#include + +#include "form_provider_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderStub + * form provider service stub. + */ +class FormProviderStub : public IRemoteStub { +public: + FormProviderStub(); + virtual ~FormProviderStub(); + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief handle AcquireProviderFormInfo message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleAcquireProviderFormInfo(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormDelete(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormsDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormsDelete(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormUpdate(MessageParcel &data, MessageParcel &reply); + + /** + * @brief handle EventNotify message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleEventNotify(MessageParcel &data, MessageParcel &reply); + + /** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleNotifyFormCastTempForm(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleFireFormEvent(MessageParcel &data, MessageParcel &reply); +private: + using FormProviderFunc = int32_t (FormProviderStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormProviderStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_PROVIDER_STUB_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_interface.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..93b634717dba54234d7a861a8228e6c1a4869d25 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_interface.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_INTERFACE_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_INTERFACE_H + +#include + +#include "form_provider_info.h" +#include "ipc_types.h" +#include "iremote_broker.h" + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; + +/** + * @class IFormSupply + * IFormSupply interface is used to access form supply service. + */ +class IFormSupply : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormSupply"); + + /** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnAcquire(const FormProviderInfo &formInfo, const Want &want) = 0; + + /** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnEventHandle(const Want &want) = 0; + + enum class Message { + // ipc id 1-1000 for kit + // ipc id 1001-2000 for DMS + // ipc id 2001-3000 for tools + // ipc id for create (3201) + TRANSACTION_FORM_ACQUIRED = 3201, + TRANSACTION_EVENT_HANDLE, + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_INTERFACE_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_proxy.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..095130a67388efb2f98ce1f554e129fa6f2d6063 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_proxy.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_PROXY_H + +#include "app_log_wrapper.h" +#include "form_supply_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyProxy + * FormSupplyProxy is used to access form supply service. + */ +class FormSupplyProxy : public IRemoteProxy { +public: + explicit FormSupplyProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormSupplyProxy() = default; + + /** + * @brief Send form binding data from form provider to fms. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; + + /** + * @brief Send other event to fms. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnEventHandle(const Want &want) override; + +private: + template + int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_PROXY_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_stub.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..796012eb146f20167aaf092cb853a25f71678f45 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/form_supply_stub.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_STUP_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_STUP_H + +#include +#include "form_supply_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyStub + * form supply service stub. + */ +class FormSupplyStub : public IRemoteStub { +public: + FormSupplyStub(); + virtual ~FormSupplyStub(); + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + +private: + /** + * @brief handle OnAcquire message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnAcquire(MessageParcel &data, MessageParcel &reply); + /** + * @brief handle OnEventHandle message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleOnEventHandle(MessageParcel &data, MessageParcel &reply); +private: + using FormSupplyFunc = int32_t (FormSupplyStub::*)(MessageParcel &data, MessageParcel &reply); + std::map memberFuncMap_; + + DISALLOW_COPY_AND_MOVE(FormSupplyStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_FORM_SUPPLY_STUP_H diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/provider_connect_proxy.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/provider_connect_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..194c8804b30efe350816306afaeb8b5071d25a79 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/provider_connect_proxy.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_PROXY_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_PROXY_H + +#include "ability_connect_callback_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; + +/** + * @class ProviderConnectProxy + * Provider connect proxy is used to connect form ability service. + */ +class ProviderConnectProxy : public IRemoteProxy { +public: + explicit ProviderConnectProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~ProviderConnectProxy() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + /** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_PROXY_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/include/formmgr/provider_connect_stub.h b/interfaces/innerkits/appexecfwk_core/include/formmgr/provider_connect_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..c8f52b8eea7562878842cd47d860ed58653baea3 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/include/formmgr/provider_connect_stub.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_STUB_H +#define FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_STUB_H + +#include "ability_connect_callback_interface.h" +#include "iremote_object.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; + +/** + * @class ProviderConnectStub + * Form ability service stub. + */ +class ProviderConnectStub : public IRemoteStub { +public: + ProviderConnectStub() = default; + virtual ~ProviderConnectStub() = default; + /** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + DISALLOW_COPY_AND_MOVE(ProviderConnectStub); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_FORMMGR_PROVIDER_CONNECT_STUB_H diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_process_data.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_process_data.cpp index dfb3cc85db06987271c8cbfb092d2e8cebb39a47..4f3c27071da06749c1738bd0d263f55aaba95aae 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_process_data.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_process_data.cpp @@ -23,7 +23,7 @@ namespace AppExecFwk { bool AppProcessData::Marshalling(Parcel &parcel) const { return (parcel.WriteString(appName) && parcel.WriteString(processName) && - parcel.WriteInt32(static_cast(appState)) && parcel.WriteInt32(pid)); + parcel.WriteInt32(static_cast(appState)) && parcel.WriteInt32(pid) && parcel.WriteInt32(uid)); } bool AppProcessData::ReadFromParcel(Parcel &parcel) @@ -36,6 +36,8 @@ bool AppProcessData::ReadFromParcel(Parcel &parcel) pid = parcel.ReadInt32(); + uid = parcel.ReadInt32(); + return true; } diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp index 4a4ae766dbd36372c200efef3b8863805da65a83..f1fb6a7eb1328a5bbfac9c8fb8b84ce088307e86 100755 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp @@ -86,6 +86,9 @@ int BundleMgrHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessagePa case static_cast(IBundleMgr::Message::QUERY_ABILITY_INFO): errCode = HandleQueryAbilityInfo(data, reply); break; + case static_cast(IBundleMgr::Message::QUERY_ABILITY_INFOS): + errCode = HandleQueryAbilityInfos(data, reply); + break; case static_cast(IBundleMgr::Message::QUERY_ABILITY_INFO_BY_URI): errCode = HandleQueryAbilityInfoByUri(data, reply); break; @@ -194,6 +197,12 @@ int BundleMgrHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessagePa case static_cast(IBundleMgr::Message::GET_SHORTCUT_INFO): errCode = HandleGetShortcutInfos(data, reply); break; + case static_cast(IBundleMgr::Message::GET_MODULE_USAGE_RECORD): + errCode = HandleGetModuleUsageRecords(data, reply); + break; + case static_cast(IBundleMgr::Message::NOTIFY_ACTIVITY_LIFE_STATUS): + errCode = HandleNotifyActivityLifeStatus(data, reply); + break; default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } @@ -432,6 +441,29 @@ ErrCode BundleMgrHost::HandleQueryAbilityInfo(Parcel &data, Parcel &reply) return ERR_OK; } +ErrCode BundleMgrHost::HandleQueryAbilityInfos(Parcel &data, Parcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + std::vector abilityInfos; + bool ret = QueryAbilityInfos(*want, abilityInfos); + if (!reply.WriteBool(ret)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (ret) { + if (!WriteParcelableVector(abilityInfos, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return ERR_OK; +} + ErrCode BundleMgrHost::HandleQueryAbilityInfoByUri(Parcel &data, Parcel &reply) { std::string abilityUri = data.ReadString(); @@ -1022,7 +1054,51 @@ ErrCode BundleMgrHost::HandleGetShortcutInfos(Parcel &data, Parcel &reply) return ERR_OK; } -template +ErrCode BundleMgrHost::HandleGetModuleUsageRecords(Parcel &data, Parcel &reply) +{ + int32_t number = data.ReadInt32(); + std::vector records; + bool ret = GetModuleUsageRecords(number, records); + if (!reply.WriteBool(ret)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (ret) { + if (!WriteParcelableVector(records, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return ERR_OK; +} + +ErrCode BundleMgrHost::HandleNotifyActivityLifeStatus(Parcel &data, Parcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string abilityName = data.ReadString(); + int64_t launchTime = data.ReadInt64(); +#if __WORDSIZE == 64 + APP_LOGI("bundleName %{public}s, abilityName %{public}s, launchTime %{public}ld", + bundleName.c_str(), + abilityName.c_str(), + launchTime); +#else + APP_LOGI("bundleName %{public}s, abilityName %{public}s, launchTime %{public}lld", + bundleName.c_str(), + abilityName.c_str(), + launchTime); +#endif + + bool ret = NotifyActivityLifeStatus(bundleName, abilityName, launchTime); + if (!reply.WriteBool(ret)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + return ERR_OK; +} + +template bool BundleMgrHost::WriteParcelableVector(std::vector &parcelableVector, Parcel &reply) { if (!reply.WriteInt32(parcelableVector.size())) { diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp index a80f71e9dac9c310139e8de8c93bcad6d3a40a80..52b27df27bb38e05c699c197d687b38e2ac52580 100644 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp @@ -367,6 +367,25 @@ bool BundleMgrProxy::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo return true; } +bool BundleMgrProxy::QueryAbilityInfos(const Want &want, std::vector &abilityInfos) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to QueryAbilityInfo due to write MessageParcel fail"); + return false; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("fail to QueryAbilityInfo due to write want fail"); + return false; + } + + if (!GetParcelableInfos(IBundleMgr::Message::QUERY_ABILITY_INFOS, data, abilityInfos)) { + APP_LOGE("fail to QueryAbilityInfos from server"); + return false; + } + return true; +} + bool BundleMgrProxy::QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) { MessageParcel data; @@ -1104,7 +1123,7 @@ bool BundleMgrProxy::RequestPermissionFromUser( } MessageParcel reply; - if (!SendTransactCmd(IBundleMgr::Message::CAN_REQUEST_PERMISSION, data, reply)) { + if (!SendTransactCmd(IBundleMgr::Message::REQUEST_PERMISSION_FROM_USER, data, reply)) { APP_LOGE("fail to RequestPermissionsFromUser from server"); return false; } @@ -1288,6 +1307,62 @@ bool BundleMgrProxy::GetShortcutInfos(const std::string &bundleName, std::vector return true; } +bool BundleMgrProxy::GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to GetModuleUsageRecords due to write MessageParcel fail"); + return false; + } + + if (!data.WriteInt32(number)) { + APP_LOGE("fail to GetModuleUsageRecords due to write number fail"); + return false; + } + + if (!GetParcelableInfos(IBundleMgr::Message::GET_MODULE_USAGE_RECORD, data, moduleUsageRecords)) { + APP_LOGE("fail to GetModuleUsageRecords from server"); + return false; + } + return true; +} + +bool BundleMgrProxy::NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) +{ + APP_LOGI("begin to NotifyActivityLifeStatus of %{public}s", abilityName.c_str()); + if (bundleName.empty() || abilityName.empty()) { + APP_LOGE("fail to NotifyActivityLifeStatus due to params empty"); + return false; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to NotifyActivityLifeStatus due to write InterfaceToken fail"); + return false; + } + if (!data.WriteString(bundleName)) { + APP_LOGE("fail to NotifyActivityLifeStatus due to write bundleName fail"); + return false; + } + if (!data.WriteString(abilityName)) { + APP_LOGE("fail to NotifyActivityLifeStatus due to write abilityName fail"); + return false; + } + if (!data.WriteInt64(launchTime)) { + APP_LOGE("fail to NotifyActivityLifeStatus due to write launchTime fail"); + return false; + } + + MessageParcel reply; + if (!SendTransactCmd(IBundleMgr::Message::NOTIFY_ACTIVITY_LIFE_STATUS, data, reply)) { + APP_LOGE("fail to NotifyActivityLifeStatus from server"); + return false; + } + return reply.ReadBool(); + +} + template bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) { diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_monitor.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_monitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..543ac97fb47a2265f752e7b018ea88bf1436878f --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_monitor.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 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 "bundle_monitor.h" + +namespace OHOS { +namespace AppExecFwk { + +BundleMonitor::BundleMonitor(const EventFwk::CommonEventSubscribeInfo &subscribeInfo) + : EventFwk::CommonEventSubscriber(subscribeInfo) +{ + APP_LOGI("BundleMonitor constructor with subscribeInfo"); +} + +bool BundleMonitor::Subscribe(const sptr &callback) +{ + APP_LOGI("Subscribe called"); + callback_ = callback; + + if (EventFwk::CommonEventManager::SubscribeCommonEvent(shared_from_this()) != true) { + APP_LOGE("SubscribeCommonEvent occur exception."); + return false; + } + return true; +} + +bool BundleMonitor::UnSubscribe() +{ + APP_LOGI("unsubscribe called"); + if (EventFwk::CommonEventManager::UnSubscribeCommonEvent(shared_from_this()) != true) { + APP_LOGE("UnsubscribeCommonEvent occur exception."); + return false; + } + return true; +} + +void BundleMonitor::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + APP_LOGI("OnReceiveEvent common event onReceiveEvent called"); + Want want = eventData.GetWant(); + std::string action = want.GetAction(); + std::string bundleName = want.GetElement().GetBundleName(); + int userId = want.GetIntParam(USER_ID, Constants::INVALID_USERID); + APP_LOGI("OnReceiveEvent action = %{public}s, bundle = %{public}s", action.c_str(), bundleName.c_str()); + if ((action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED) && (callback_ != nullptr)) { + callback_->OnBundleAdded(bundleName, userId); + } else if ((action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) && (callback_ != nullptr)) { + callback_->OnBundleUpdated(bundleName, userId); + } else if ((action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) && (callback_ != nullptr)) { + callback_->OnBundleRemoved(bundleName, userId); + } else { + APP_LOGI("OnReceiveEvent action = %{public}s not support", action.c_str()); + } +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16753cb5a2898e2ca612e1e45c345175e828495d --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2021 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 "launcher_service.h" + +#include "matching_skills.h" +#include "common_event_support.h" +#include "common_event_subscribe_info.h" +#include "operation_builder.h" + +namespace OHOS { +namespace AppExecFwk { + +LauncherService::LauncherService() +{ + init(); +} + +void LauncherService::init() +{ + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + bundleMonitor_ = std::make_shared(subscribeInfo); +} + +OHOS::sptr LauncherService::GetBundleMgr() +{ + OHOS::sptr systemAbilityManager = + OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + OHOS::sptr remoteObject = + systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + return OHOS::iface_cast(remoteObject); +} + +bool LauncherService::RegisterCallback(const sptr &callback) +{ + APP_LOGI("RegisterCallback called"); + if (bundleMonitor_ == nullptr) { + APP_LOGE("failed to register callback, bundleMonitor is null"); + return false; + } + + return bundleMonitor_->Subscribe(callback); +} + +bool LauncherService::UnRegisterCallback() +{ + APP_LOGI("UnRegisterCallback called"); + if (bundleMonitor_ == nullptr) { + APP_LOGE("failed to unregister callback, bundleMonitor is null"); + return false; + } + + return bundleMonitor_->UnSubscribe(); +} + +bool LauncherService::GetAbilityList( + const std::string &bundleName, const int userId, std::vector &launcherAbilityInfos) +{ + APP_LOGI("GetAbilityList called"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("can not get iBundleMgr"); + return false; + } + + std::vector entities; + entities.push_back(Want::ENTITY_HOME); + Want want; + OHOS::AAFwk::OperationBuilder opBuilder; + auto operation = opBuilder.WithAction(Want::ACTION_HOME).WithEntities(entities).build(); + want.SetOperation(*operation); + ElementName elementName; + elementName.SetBundleName(bundleName); + want.SetElement(elementName); + std::vector abilityInfo; + if (!iBundleMgr->QueryAbilityInfos(want, abilityInfo)) { + APP_LOGE("Query ability info failed"); + return false; + } + + std::string icon = ""; + ApplicationInfo appInfo; + ApplicationFlag flag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; + if (!iBundleMgr->GetApplicationInfo(bundleName, flag, Constants::DEFAULT_USERID, appInfo)) { + APP_LOGE("Get application info failed"); + return false; + } + icon = appInfo.iconId; + + int64_t installTime = 0; + BundleFlag flags; + flags = BundleFlag::GET_BUNDLE_WITH_ABILITIES; + BundleInfo bundleInfo; + if (!iBundleMgr->GetBundleInfo(bundleName, flags, bundleInfo)) { + APP_LOGE("Get bundle info failed"); + return false; + } + installTime = bundleInfo.installTime; + + for (auto &ability : abilityInfo) { + LauncherAbilityInfo info; + info.name = ability.name; + info.applicationInfo = ability.applicationInfo; + info.label = ability.label; + ElementName elementName; + elementName.SetBundleName(ability.bundleName); + elementName.SetAbilityName(ability.name); + elementName.SetDeviceID(ability.deviceId); + info.elementname = elementName; + info.icon = icon; + info.userid = userId; + info.installTime = installTime; + launcherAbilityInfos.emplace_back(info); + } + + return true; +} + +bool LauncherService::GetAbilityInfo(const Want &want, const int userId, LauncherAbilityInfo &launcherAbilityInfo) +{ + APP_LOGI("GetAbilityInfo called"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("can not get iBundleMgr"); + return false; + } + ElementName element = want.GetElement(); + if (element.GetBundleName().empty() || element.GetAbilityName().empty()) { + APP_LOGE("GetAbilityInfo elementName is empty"); + return false; + } + AbilityInfo abilityInfo; + if (!iBundleMgr->QueryAbilityInfo(want, abilityInfo)) { + APP_LOGE("Query AbilityInfo failed"); + return false; + } + + std::string bundleName = element.GetBundleName(); + std::string icon = ""; + ApplicationInfo appInfo; + ApplicationFlag flag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; + if (!iBundleMgr->GetApplicationInfo(bundleName, flag, Constants::DEFAULT_USERID, appInfo)) { + APP_LOGE("Get application info failed"); + return false; + } + icon = appInfo.iconId; + + int64_t installTime = 0; + BundleFlag flags; + flags = BundleFlag::GET_BUNDLE_WITH_ABILITIES; + BundleInfo bundleInfo; + if (!iBundleMgr->GetBundleInfo(bundleName, flags, bundleInfo)) { + APP_LOGE("Get bundle info failed"); + return false; + } + installTime = bundleInfo.installTime; + + LauncherAbilityInfo info; + info.name = abilityInfo.name; + info.applicationInfo = abilityInfo.applicationInfo; + info.label = abilityInfo.label; + ElementName elementName; + elementName.SetBundleName(abilityInfo.bundleName); + elementName.SetAbilityName(abilityInfo.name); + elementName.SetDeviceID(abilityInfo.deviceId); + info.elementname = elementName; + info.icon = icon; + info.userid = userId; + info.installTime = installTime; + launcherAbilityInfo = info; + + return true; +} + +bool LauncherService::GetApplicationInfo( + const std::string &bundleName, const ApplicationFlag &flags, const int userId, ApplicationInfo &applicationInfo) +{ + APP_LOGI("GetApplicationInfo called"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("can not get iBundleMgr"); + return false; + } + if (bundleName.empty()) { + APP_LOGE("GetApplicationInfo bundleName is empty"); + return false; + } + + if (!iBundleMgr->GetApplicationInfo(bundleName, flags, userId, applicationInfo)) { + APP_LOGE("Get application info failed"); + return false; + } + + return true; +} + +bool LauncherService::IsBundleEnabled(const std::string &bundleName) +{ + APP_LOGI("IsBundleEnabled called"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("can not get iBundleMgr"); + return false; + } + if (bundleName.empty()) { + APP_LOGE("bundleName is empty"); + return false; + } + + return iBundleMgr->IsApplicationEnabled(bundleName); +} + +bool LauncherService::IsAbilityEnabled(const AbilityInfo &abilityInfo) +{ + APP_LOGI("IsAbilityEnabled called"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("can not get iBundleMgr"); + return false; + } + + return iBundleMgr->IsAbilityEnabled(abilityInfo); +} + +bool LauncherService::GetShortcutInfos( + const std::string &bundleName, std::vector &launcherShortcutInfo) +{ + APP_LOGI("GetShortcutInfos called"); + if (bundleName.empty()) { + APP_LOGE("bundleName is empty"); + return false; + } + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("can not get iBundleMgr"); + return false; + } + + std::vector infos; + if (!iBundleMgr->GetShortcutInfos(bundleName, infos)) { + APP_LOGE("Get shortcut infos failed"); + return false; + } + if (infos.size() == 0) { + APP_LOGE("ShortcutInfo is not exist in system"); + return false; + } + + for (ShortcutInfo shortcutInfo : infos) { + if (bundleName == shortcutInfo.bundleName) { + LauncherShortcutInfo launchershortcutinfo; + launchershortcutinfo.bundleName = shortcutInfo.bundleName; + launchershortcutinfo.icon = shortcutInfo.icon; + launchershortcutinfo.intents = shortcutInfo.intents; + launchershortcutinfo.label = shortcutInfo.label; + launchershortcutinfo.shortcutid = shortcutInfo.id; + launcherShortcutInfo.emplace_back(launchershortcutinfo); + } + } + return true; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c414aa53299a13264100fe6f48e1df3e29ebdfc9 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "form_host_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Request to give back a Form. + * @param formInfo Form info. + */ +void FormHostProxy::OnAcquired(const FormJsInfo &formInfo) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + } + + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + } + + error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED), data, reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } +} + + +/** +* @brief Form is updated. +* @param bundleName Provider ability bundleName. +*/ +void FormHostProxy::OnUpdate(const FormJsInfo &formInfo) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + } + + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + } + + error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_UPDATE), data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } +} + + +/** + * @brief Form provider is uninstalled + * @param formIds The Id list of the forms. + */ +void FormHostProxy::OnUninstall(const std::vector &formIds) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + } + + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds", __func__); + } + + error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL), data, reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } +} + +template +int FormHostProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to read Parcelable infos", __func__); + return ERR_NULL_OBJECT; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("%{public}s, get parcelable infos success", __func__); + return ERR_OK; +} + +bool FormHostProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormHostProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce0612183151a8386f79aa061bab8c4384dc133f --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "app_scheduler_interface.h" +#include "errors.h" +#include "form_host_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormHostStub::FormHostStub() +{ + memberFuncMap_[static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED)] = + &FormHostStub::HandleAcquired; + memberFuncMap_[static_cast(IFormHost::Message::FORM_HOST_ON_UPDATE)] = + &FormHostStub::HandleOnUpdate; + memberFuncMap_[static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL)] = + &FormHostStub::HandleOnUninstall; +} + +FormHostStub::~FormHostStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormHostStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormHostStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle OnAcquired event. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::HandleAcquired(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr formInfo(data.ReadParcelable()); + if (!formInfo) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + OnAcquired(*formInfo); + reply.WriteInt32(ERR_OK); + return ERR_OK; +} +/** + * @brief handle OnUpdate event. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::HandleOnUpdate(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr formInfo(data.ReadParcelable()); + if (!formInfo) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + OnUpdate(*formInfo); + reply.WriteInt32(ERR_OK); + return ERR_OK; +} + +/** + * @brief handle OnUnInstall event. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormHostStub::HandleOnUninstall(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (ret) { + OnUninstall(formIds); + reply.WriteInt32(ERR_OK); + return ERR_OK; + } + return ERR_INVALID_DATA; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..606a06c01288fa3b823e842906b86e563726df1d --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp @@ -0,0 +1,562 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_mgr_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +FormMgrProxy::FormMgrProxy(const sptr &impl) : IRemoteProxy(impl) +{} +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetParcelableInfo(IFormMgr::Message::FORM_MGR_ADD_FORM, data, formInfo); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + + return error; +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM), data, reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + +/** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteBool(delCache)) { + APP_LOGE("%{public}s, failed to write delCache", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM), data, reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param FormProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::UpdateForm(const int64_t formId, const std::string &bundleName, +const FormProviderData &FormProviderData) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&FormProviderData)) { + APP_LOGE("%{public}s, failed to write formBindingData", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM), data, reply, + option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + +/** + * @brief Set next refresh time. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + MessageParcel data; + MessageParcel reply; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(nextTime)) { + APP_LOGE("%{public}s, failed to write nextTime", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME), data, + reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} +/** + * @brief Lifecycle update. + * @param formIds The Id of the forms. + * @param callerToken Caller ability token. + * @param updateType update type. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, +const int32_t updateType) +{ + MessageParcel data; + MessageParcel reply; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt32(updateType)) { + APP_LOGE("%{public}s, failed to write nextTime", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + + return reply.ReadInt32(); +} +/** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::NotifyWhetherVisibleForms(const std::vector &formIds, +const sptr &callerToken, const int32_t formVisibleType) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt32(formVisibleType)) { + APP_LOGE("%{public}s, failed to write formVisibleType", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + +/** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DumpStorageFormInfos(std::string &formInfos) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetStringInfo(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS, data, formInfos); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + } + + return error; +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteString(bundleName)) { + APP_LOGE("%{public}s, failed to write bundleName", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME, data, formInfos); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + } + + return error; +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrProxy::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int error = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to GetStringInfo: %{public}d", __func__, error); + } + + return error; +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgrProxy::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), data, + reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return reply.ReadInt32(); +} + +template +int FormMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to Read Parcelable infos", __func__); + return ERR_NULL_OBJECT; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("get parcelable infos success"); + return ERR_OK; +} +bool FormMgrProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(IFormMgr::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +int FormMgrProxy::GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to read reply result", __func__); + return error; + } + std::vector stringInfoList; + if (!reply.ReadStringVector(&stringInfoList)) { + APP_LOGE("%{public}s, failed to read string vector from reply", __func__); + return false; + } + if (stringInfoList.empty()) { + APP_LOGI("%{public}s, No string info", __func__); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + for (auto &info : stringInfoList) { + stringInfo += info; + } + APP_LOGD("get string info success"); + return ERR_OK; +} +template +int FormMgrProxy::GetParcelableInfo(IFormMgr::Message code, MessageParcel &data, T &parcelableInfo) +{ + int error; + MessageParcel reply; + error = SendTransactCmd(code, data, reply); + if (error != ERR_OK) { + return error; + } + + error = reply.ReadInt32(); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to read reply result", __func__); + return error; + } + + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to readParcelableInfo", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + parcelableInfo = *info; + APP_LOGD("get parcelable info success"); + return ERR_OK; +} +int FormMgrProxy::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply) +{ + MessageOption option(MessageOption::TF_SYNC); + + sptr remote = Remote(); + if (!remote) { + APP_LOGE("%{public}s, failed to get remote object, cmd: %{public}d", __func__, code); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + int32_t result = remote->SendRequest(static_cast(code), data, reply, option); + if (result != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code); + return result; + } + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce4f6173ab07a17d413b433bb16c04ec7eeb05ce --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_mgr_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +const int32_t LIMIT_PARCEL_SIZE = 1024; + +void SplitString(const std::string &source, std::vector &strings) +{ + int splitSize = (source.size() / LIMIT_PARCEL_SIZE); + if ((source.size() % LIMIT_PARCEL_SIZE) != 0) { + splitSize++; + } + APP_LOGD("the dump string split into %{public}d size", splitSize); + for (int i = 0; i < splitSize; i++) { + int32_t start = LIMIT_PARCEL_SIZE * i; + strings.emplace_back(source.substr(start, LIMIT_PARCEL_SIZE)); + } +} + +FormMgrStub::FormMgrStub() +{ + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_ADD_FORM)] = + &FormMgrStub::HandleAddForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM)] = + &FormMgrStub::HandleDeleteForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM)] = + &FormMgrStub::HandleReleaseForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM)] = + &FormMgrStub::HandleUpdateForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM)] = + &FormMgrStub::HandleRequestForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE)] = + &FormMgrStub::HandleNotifyWhetherVisibleForms; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM)] = + &FormMgrStub::HandleCastTempForm; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS)] = + &FormMgrStub::HandleDumpStorageFormInfos; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME)] = + &FormMgrStub::HandleDumpFormInfoByBundleName; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID)] = + &FormMgrStub::HandleDumpFormInfoByFormId; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME)] = + &FormMgrStub::HandleSetNextRefreshTime; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE)] = + &FormMgrStub::HandleLifecycleUpdate; + memberFuncMap_[static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT)] = + &FormMgrStub::HandleMessageEvent; +} + +FormMgrStub::~FormMgrStub() +{ + memberFuncMap_.clear(); +} + +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormMgrStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormMgrStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle AddForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleAddForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to RemoteObject invalidate", __func__); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + + FormJsInfo formInfo; + int32_t result = AddForm(formId, *want, client, formInfo); + reply.WriteInt32(result); + reply.WriteParcelable(&formInfo); + + return result; +} +/** + * @brief handle DeleteForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDeleteForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + int32_t result = DeleteForm(formId, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle ReleaseForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleReleaseForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + bool delCache = data.ReadBool(); + + int32_t result = ReleaseForm(formId, client, delCache); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle UpdateForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleUpdateForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::string bundleName = data.ReadString(); + std::unique_ptr formBindingData(data.ReadParcelable()); + int32_t result = UpdateForm(formId, bundleName, *formBindingData); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle SetNextRefreshTime message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleSetNextRefreshTime(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + int64_t nextTime = data.ReadInt64(); + int32_t result = SetNextRefreshTime(formId, nextTime); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle LifecycleUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleLifecycleUpdate(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (!ret) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + int32_t updateType = data.ReadInt32(); + int32_t result = LifecycleUpdate(formIds, client, updateType); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle RequestForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleRequestForm(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + + int64_t formId = data.ReadInt64(); + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = RequestForm(formId, client, *want); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyVisibleForms message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleNotifyWhetherVisibleForms(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (!ret) { + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + int32_t formVisibleType = data.ReadInt32(); + + int32_t result = NotifyWhetherVisibleForms(formIds, client, formVisibleType); + reply.WriteInt32(result); + return result; +} + +/** + * @brief handle CastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleCastTempForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + sptr client = data.ReadParcelable(); + if (client == nullptr) { + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + + int32_t result = CastTempForm(formId, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief Handle DumpStorageFormInfos message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDumpStorageFormInfos(MessageParcel &data, MessageParcel &reply) +{ + std::string formInfos; + int32_t result = DumpStorageFormInfos(formInfos); + reply.WriteInt32(result); + if (result == ERR_OK) { + std::vector dumpInfos; + SplitString(formInfos, dumpInfos); + if (!reply.WriteStringVector(dumpInfos)) { + APP_LOGE("%{public}s, failed to WriteStringVector", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + return result; +} +/** + * @brief Handle DumpFormInfoByBundleName message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDumpFormInfoByBundleName(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string formInfos; + int32_t result = DumpFormInfoByBundleName(bundleName, formInfos); + reply.WriteInt32(result); + if (result == ERR_OK) { + APP_LOGD("%{public}s, formInfos: %{public}s", __func__, formInfos.c_str()); + std::vector dumpInfos; + SplitString(formInfos, dumpInfos); + if (!reply.WriteStringVector(dumpInfos)) { + APP_LOGE("%{public}s, failed to WriteStringVector", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + return result; +} +/** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleDumpFormInfoByFormId(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::string formInfo; + int32_t result = DumpFormInfoByFormId(formId, formInfo); + reply.WriteInt32(result); + if (result == ERR_OK) { + std::vector dumpInfos; + SplitString(formInfo, dumpInfos); + if (!reply.WriteStringVector(dumpInfos)) { + APP_LOGE("%{public}s, failed to WriteStringVector", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return result; +} +/** + * @brief Handle DumpFormInfoByFormId message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormMgrStub::HandleMessageEvent(MessageParcel &data, MessageParcel &reply) +{ + APP_LOGI("%{public}s called.", __func__); + + int64_t formId = data.ReadInt64(); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; + } + + int32_t result = MessageEvent(formId, *want, client); + reply.WriteInt32(result); + return result; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d94e233bc9324f79c319aeef1d9ff49d0a407a2 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "form_provider_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Acquire to give back an ProviderFormInfo. This is sync API. + * @param formId The Id of the from. + * @param want Indicates the {@link Want} structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::AcquireProviderFormInfo(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s fail, write want error", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Notify provider when the form was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} +/** + * @brief Notify provider when the forms was deleted. + * @param formIds The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormsDelete(const std::vector &formIds, const Want &want, +const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Event notify when change the form visible. + * + * @param formIds The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt64Vector(formIds)) { + APP_LOGE("%{public}s, failed to write formIds.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteInt32(formVisibleType)) { + APP_LOGE("%{public}s, failed to write formVisibleType.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken.", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Notify provider when the temp form was cast to normal form. + * @param formId The Id of the form to update. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::NotifyFormCastTempForm(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data. WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderProxy::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, +const sptr &callerToken) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteInt64(formId)) { + APP_LOGE("%{public}s, failed to write formId", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteString(message)) { + APP_LOGE("%{public}s, failed to write message", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(callerToken)) { + APP_LOGE("%{public}s, failed to write callerToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return error; + } + return ERR_OK; +} + +template +int FormProviderProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to Read Parcelable infos", __func__); + return ERR_NULL_OBJECT; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("%{public}s, get parcelable infos success", __func__); + return ERR_OK; +} + +bool FormProviderProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormProviderProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95203261c7fe4f7510dcd25ce32564438b20e9ea --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "app_scheduler_interface.h" +#include "errors.h" +#include "form_provider_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormProviderStub::FormProviderStub() +{ + memberFuncMap_[static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO)] = + &FormProviderStub::HandleAcquireProviderFormInfo; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE)] = + &FormProviderStub::HandleNotifyFormDelete; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE)] = + &FormProviderStub::HandleNotifyFormsDelete; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE)] = + &FormProviderStub::HandleNotifyFormUpdate; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY)] = + &FormProviderStub::HandleEventNotify; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST)] = + &FormProviderStub::HandleNotifyFormCastTempForm; + memberFuncMap_[static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_MESSAGE)] = + &FormProviderStub::HandleFireFormEvent; +} + +FormProviderStub::~FormProviderStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormProviderStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormProviderStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle AcquireProviderFormInfo message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleAcquireProviderFormInfo(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + int32_t result = AcquireProviderFormInfo(formId, *want, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyFormDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormDelete(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_NULL_OBJECT; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + int32_t result = NotifyFormDelete(formId, *want, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyFormsDelete message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormsDelete(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (ret) { + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_NULL_OBJECT; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + int32_t result = NotifyFormsDelete(formIds, *want, client); + reply.WriteInt32(result); + return result; + } + + return ERR_INVALID_DATA; +} +/** + * @brief handle NotifyFormUpdate message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormUpdate(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + int32_t result = NotifyFormUpdate(formId, *want, client); + reply.WriteInt32(result); + return result; +} + +/** + * @brief handle EventNotify message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleEventNotify(MessageParcel &data, MessageParcel &reply) +{ + std::vector formIds; + bool ret = data.ReadInt64Vector(&formIds); + if (ret) { + int32_t formVisibleType = data.ReadInt32(); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + int32_t result = EventNotify(formIds, formVisibleType, *want, client); + reply.WriteInt32(result); + return result; + } + + return ERR_INVALID_DATA; +} + +/** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleNotifyFormCastTempForm(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_NULL_OBJECT; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + int32_t result = NotifyFormCastTempForm(formId, *want, client); + reply.WriteInt32(result); + return result; +} +/** + * @brief handle NotifyFormCastTempForm message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormProviderStub::HandleFireFormEvent(MessageParcel &data, MessageParcel &reply) +{ + int64_t formId = data.ReadInt64(); + std::string message = data.ReadString(); + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); + return ERR_NULL_OBJECT; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_NULL_OBJECT; + } + + int32_t result = FireFormEvent(formId, message, *want, client); + reply.WriteInt32(result); + return result; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..190f65c5351d88eb2bb2419816eda8009ecf34b2 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "form_constants.h" +#include "form_supply_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Send form binding data from form provider to fms. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnAcquire(const FormProviderInfo &formInfo, const Want& want) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to WriteInterfaceToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK) == ERR_OK) { + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + + +/** + * @brief Send other event to fms. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnEventHandle(const Want& want) +{ + MessageParcel data; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + +template +int FormSupplyProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_INVALID_VALUE; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("get parcelable infos success"); + return ERR_OK; +} + +bool FormSupplyProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormSupplyProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token failed", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89061b1607048824fe3b7401a4e03a3450b72ed1 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_supply_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormSupplyStub::FormSupplyStub() +{ + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED)] = + &FormSupplyStub::HandleOnAcquire; + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE)] = + &FormSupplyStub::HandleOnEventHandle; +} + +FormSupplyStub::~FormSupplyStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormSupplyStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormSupplyStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle OnAcquire message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnAcquire(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_INVALID_VALUE); + return ERR_INVALID_VALUE; + } + + int errCode = ERR_OK; + do { + errCode = want->GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s, provider error", __func__); + break; + } + std::unique_ptr formInfo(data.ReadParcelable()); + if (formInfo == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + errCode = ERR_INVALID_VALUE; + break; + } + int32_t result = OnAcquire(*formInfo, *want); + reply.WriteInt32(result); + return result; + } while (true); + + FormProviderInfo formProviderInfo; + want->SetParam(Constants::PROVIDER_FLAG, errCode); + OnAcquire(formProviderInfo, *want); + reply.WriteInt32(errCode); + return errCode; +} +/** + * @brief handle OnEventHandle message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnEventHandle(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_INVALID_VALUE); + return ERR_INVALID_VALUE; + } + + int32_t result = OnEventHandle(*want); + reply.WriteInt32(result); + return result; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e966e7b0956e7bbb059b426619d100662773f100 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp @@ -0,0 +1,107 @@ + +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "provider_connect_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void ProviderConnectProxy::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGD("%{public}s, abilityName:%{public}s,resultCode:%{public}d", __func__, element.GetAbilityName().c_str(), resultCode); + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return; + } + + if (!data.WriteParcelable(&element)) { + APP_LOGE("%{public}s, failed to write element", __func__); + return; + } + + if (!data.WriteParcelable(remoteObject)) { + APP_LOGE("%{public}s, failed to write remote object ", __func__); + return; + } + + if (!data.WriteInt32(resultCode)) { + APP_LOGE("%{public}s, failed to write resultCode", __func__); + return; + } + + error = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return; + } +} +/** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ +void ProviderConnectProxy::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + APP_LOGD("%{public}s, element:%{public}s, resultCode:%{public}d", __func__, element.GetURI().c_str(), resultCode); + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return; + } + if (!data.WriteParcelable(&element)) { + APP_LOGE("%{public}s, failed to write element", __func__); + return; + } + if (!data.WriteInt32(resultCode)) { + APP_LOGE("%{public}s, failed to write resultCode", __func__); + return; + } + + error = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_DISCONNECT_DONE, data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + return; + } +} + +bool ProviderConnectProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(ProviderConnectProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54323fdac89f43458456d34608c438637a6034c5 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp @@ -0,0 +1,74 @@ + +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "provider_connect_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int ProviderConnectStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::u16string descriptor = ProviderConnectStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGI("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_INVALID_STATE; + } + + auto element = data.ReadParcelable(); + switch (code) { + case IAbilityConnection::ON_ABILITY_CONNECT_DONE: { + if (element == nullptr) { + APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); + return ERR_INVALID_VALUE; + } + auto remoteObject = data.ReadParcelable(); + auto resultCode = data.ReadInt32(); + OnAbilityConnectDone(*element, remoteObject, resultCode); + delete element; + return ERR_OK; + } + case IAbilityConnection::ON_ABILITY_DISCONNECT_DONE: { + if (element == nullptr) { + APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); + return ERR_INVALID_VALUE; + } + auto resultCode = data.ReadInt32(); + OnAbilityDisconnectDone(*element, resultCode); + delete element; + return ERR_OK; + } + default: { + if (element != nullptr) { + delete element; + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/fmskit/BUILD.gn b/interfaces/innerkits/fmskit/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8a3085fa9bee1b63c26c644c04f85deff8a8b87c --- /dev/null +++ b/interfaces/innerkits/fmskit/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2021 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") +SUBSYSTEM_DIR = "//foundation/appexecfwk/standard" + +config("fmskit_config") { + defines = [ + "APP_LOG_TAG = \"FmskitNative\"", + "LOG_DOMAIN = 0xD001151", + ] + + include_dirs = [ "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include" ] +} +config("public_fmskit_config") { + include_dirs = [ + "$SUBSYSTEM_DIR/common/log/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//utils/system/safwk/native/include", + ] +} + +# build so +ohos_shared_library("fmskit_native") { + configs = [ ":fmskit_config" ] + public_configs = [ ":public_fmskit_config" ] + sources = [ + "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_host_client.cpp", + "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "$SUBSYSTEM_DIR/common:libappexecfwk_common", + "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "$SUBSYSTEM_DIR/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/interfaces/innerkits/fmskit/native/include/form_callback_interface.h b/interfaces/innerkits/fmskit/native/include/form_callback_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..458a143986ab082b03785e533336eccba99dc673 --- /dev/null +++ b/interfaces/innerkits/fmskit/native/include/form_callback_interface.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_ABILITY_INTERFACE_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_ABILITY_INTERFACE_H + +#include "form_js_info.h" + +namespace OHOS { +namespace AppExecFwk { +class FormCallbackInterface { +public: + /** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + virtual void ProcessFormUpdate(const FormJsInfo &formJsInfo) = 0; + + /** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ + virtual void ProcessFormUninstall(const int64_t formId) = 0; + + /** + * @brief Form service death event. + * + */ + virtual void OnDeathReceived() = 0; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_ABILITY_INTERFACE_H diff --git a/interfaces/innerkits/fmskit/native/include/form_host_client.h b/interfaces/innerkits/fmskit/native/include/form_host_client.h new file mode 100755 index 0000000000000000000000000000000000000000..beebbe2c12fee0c77e4e79080a6af40afb9aa612 --- /dev/null +++ b/interfaces/innerkits/fmskit/native/include/form_host_client.h @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H + +#include +#include +#include +#include +#include "form_callback_interface.h" +#include "form_host_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostClient + * The service of the form host. + */ +class HostForms; +class FormHostClient : public FormHostStub { +public: + FormHostClient(); + virtual ~FormHostClient(); + + /** + * @brief Get FormHostClient instance. + * + * @return FormHostClient instance. + */ + static sptr GetInstance(); + + /** + * @brief Add form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ + void AddForm(std::shared_ptr formCallback, const int64_t formId); + + /** + * @brief Remove form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ + void RemoveForm(std::shared_ptr formCallback, const int64_t formId); + + /** + * @brief Check whether the form exist in the formhosts. + * + * @param formId The Id of the form. + * @return Returns true if contains form; returns false otherwise. + */ + bool ContainsForm(int64_t formId); + + /** + * @brief Request to give back a form. + * + * @param formJsInfo Form js info. + * @return none. + */ + virtual void OnAcquired(const FormJsInfo &formJsInfo); + + /** + * @brief Update form. + * + * @param formJsInfo Form js info. + * @return none. + */ + virtual void OnUpdate(const FormJsInfo &formJsInfo); + + /** + * @brief UnInstall the forms. + * + * @param formIds The Id of the forms. + * @return none. + */ + virtual void OnUninstall(const std::vector &formIds); + +private: + static sptr instance_; + static std::mutex instanceMutex_; + mutable std::mutex lockMutex_; + std::vector keyVector_; + std::map> recordCallback_; + std::map recordHostForms_; + int32_t key_ = 0; + +private: + /** + * @brief Find callback by formId. + * + * @param formId The Id of the form. + * @return target callback + */ + std::shared_ptr FindTargetCallback(int64_t formId); + + /** + * @brief Find Key By form callback. + * + * @param formCallback The form callback. + * @return callback's key + */ + int32_t FindKeyByCallback(std::shared_ptr formCallback); + + /** + * @brief Compare callback. + * + * @param formCallback1 The form callback1. + * @param formCallback2 The callback to be compared with form callback1. + * @return Returns true if the two callback are equal to each other, returns false otherwise. + */ + bool Compare(std::shared_ptr formCallback1, std::shared_ptr formCallback2); + + DISALLOW_COPY_AND_MOVE(FormHostClient); +}; + +class HostForms { +public: + /** + * @brief Add form by formId. + * + * @param formId The Id of the form. + */ + void AddForm(const int64_t formId) + { + std::map::iterator it = forms_.find(formId); + if (it != forms_.end()) { + return; + } + forms_.insert(std::pair(formId, true)); + } + + /** + * @brief Delete form by formId. + * + * @param formId The Id of the form. + */ + void DelForm(const int64_t formId) + { + forms_.erase(formId); + } + + /** + * @brief Check whether the form is empty. + */ + bool IsEmpty() + { + return forms_.empty(); + } + + /** + * @brief Check whether the form exist in the forms. + * + * @param formId The Id of the form. + * @return Returns true if contains form; returns false otherwise. + */ + bool Contains(const int64_t formId) + { + std::map::iterator it = forms_.find(formId); + return (it == forms_.end()) ? false : true; + } + +private: + std::map forms_; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H diff --git a/interfaces/innerkits/fmskit/native/include/form_mgr.h b/interfaces/innerkits/fmskit/native/include/form_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..4eaca5087e5ccc0b738caa37b40ca7ed4461bae3 --- /dev/null +++ b/interfaces/innerkits/fmskit/native/include/form_mgr.h @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_MGR_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_MGR_H + +#include +#include + +#include "form_callback_interface.h" +#include "form_constants.h" +#include "form_death_callback.h" +#include "form_js_info.h" +#include "form_mgr_interface.h" +#include "form_provider_data.h" +#include "iremote_object.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using OHOS::AAFwk::Want; + +static volatile int recoverStatus_ = Constants::NOT_IN_RECOVERY; + +/** + * @class FormMgr + * FormMgr is used to access form manager services. + */ +class FormMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormMgr) +public: + DISALLOW_COPY_AND_MOVE(FormMgr); + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo); + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DeleteForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache); + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formBindingData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const std::string &bundleName, const FormProviderData &formBindingData); + + /** + * @brief Notify the form service that the form user's lifecycle is updated. + * + * This should be called when form user request form. + * + * @param formId Indicates the unique id of form. + * @param callerToken Indicates the callback remote object of specified form user. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ + int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want); + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType); + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return None. + */ + int CastTempForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpStorageFormInfos(std::string &formInfos); + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByBundleName(const std::string bundleName, std::string &formInfos); + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo); + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken); + + /** + * @brief Get fms recoverStatus. + * + * @return The current recover status. + */ + static int GetRecoverStatus(); + + /** + * @brief Register death callback. + * + * @param formDeathCallback The death callback. + */ + void RegisterDeathCallback(const std::shared_ptr &formDeathCallback); + + /** + * @brief UnRegister death callback. + * + * @param formDeathCallback The death callback. + */ + void UnRegisterDeathCallback(const std::shared_ptr &formDeathCallback); + + int SetNextRefreshTime(const int64_t formId, const int64_t nextTime); + + /** + * @brief Lifecycle Update. + * @param formIds The id of the forms. + * @param callerToken Host client. + * @param updateType Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType); + + /** + * @brief Set fms recoverStatus. + * + * @param recoverStatus The recover status. + */ + static void SetRecoverStatus(int recoverStatus); + + /** + * @brief Set form mgr service for test. + */ + void SetFormMgrService(sptr formMgrService); + + /** + * @brief Get death recipient. + * @return deathRecipient_. + */ + sptr GetDeathRecipient() const; + + /** + * @brief Check whether the specified death callback is registered in form mgr. + * @param formDeathCallback The specified death callback for checking. + * @return Return true on success, false on failure. + */ + bool CheckIsDeathCallbackRegistered(const std::shared_ptr &formDeathCallback); + +private: + /** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode Connect(); + + /** + * @brief Reconnect form manager service once per 1000 milliseconds, + * until the connection succeeds or reaching the max retry times. + * @return Returns true if execute success, false otherwise. + */ + bool Reconnect(); + /** + * @brief Reset proxy. + * @param remote remote object. + */ + void ResetProxy(const wptr &remote); + +public: + friend class FormMgrDeathRecipient; + +private: + /** + * @class FormMgrDeathRecipient + * FormMgrDeathRecipient notices IRemoteBroker died. + */ + class FormMgrDeathRecipient : public IRemoteObject::DeathRecipient { + public: + FormMgrDeathRecipient() = default; + ~FormMgrDeathRecipient() = default; + + /** + * @brief Notices IRemoteBroker died. + * @param remote remote object. + */ + void OnRemoteDied(const wptr &remote) override; + private: + DISALLOW_COPY_AND_MOVE(FormMgrDeathRecipient); + }; + + std::mutex connectMutex_; + sptr remoteProxy_; + + sptr deathRecipient_ {nullptr}; + + // True: need to get a new fms remote object, + // False: no need to get a new fms remote object. + volatile bool resetFlag_ = false; + + std::vector> formDeathCallbacks_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_MGR_H \ No newline at end of file diff --git a/interfaces/innerkits/fmskit/native/src/form_host_client.cpp b/interfaces/innerkits/fmskit/native/src/form_host_client.cpp new file mode 100755 index 0000000000000000000000000000000000000000..a506bb158d4b5dab414ab0003713ff7a1836a90f --- /dev/null +++ b/interfaces/innerkits/fmskit/native/src/form_host_client.cpp @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_host_client.h" + +namespace OHOS { +namespace AppExecFwk { +sptr FormHostClient::instance_ = nullptr; +std::mutex FormHostClient::instanceMutex_; + +FormHostClient::FormHostClient() +{ +} + +FormHostClient::~FormHostClient() +{ +} + +/** + * @brief Get FormHostClient instance. + * + * @return FormHostClient instance. + */ +sptr FormHostClient::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(instanceMutex_); + if (instance_ == nullptr) { + instance_ = new FormHostClient(); + } + } + return instance_; +} + +/** + * @brief Add form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ +void FormHostClient::AddForm(std::shared_ptr formCallback, const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative or zero.", __func__); + return; + } + + { + std::lock_guard lock(lockMutex_); + int64_t key = FindKeyByCallback(formCallback); + if (key == -1) { + HostForms hostForms; + int64_t tempKey = key_; + if (!keyVector_.empty()) { + tempKey = keyVector_.back(); + keyVector_.pop_back(); + } + hostForms.AddForm(formId); + recordCallback_.insert(std::make_pair(tempKey, formCallback)); + recordHostForms_.insert(std::make_pair(tempKey, hostForms)); + + if (tempKey == key_) { + key_++; + } + } else { + recordHostForms_[key].AddForm(formId); + } + } +} + +/** + * @brief Remove form. + * + * @param formCallback the host's form callback. + * @param formId The Id of the form. + * @return none. + */ +void FormHostClient::RemoveForm(std::shared_ptr formCallback, const int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0 || formCallback == nullptr) { + APP_LOGE("%{public}s, invalid param.", __func__); + return; + } + + { + std::lock_guard lock(lockMutex_); + int64_t key = FindKeyByCallback(formCallback); + if(key == -1) { + APP_LOGE("%{public}s, failed to find callback.", __func__); + return; + } + + if (recordHostForms_[key].IsEmpty()) { + recordCallback_.erase(key); + recordHostForms_.erase(key); + keyVector_.push_back(key); + APP_LOGI("%{public}s, clear data.", __func__); + return; + } + + recordHostForms_[key].DelForm(formId); + if (recordHostForms_[key].IsEmpty()) { + recordCallback_.erase(key); + recordHostForms_.erase(key); + keyVector_.push_back(key); + APP_LOGI("%{public}s, clear data.", __func__); + } + } + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Check whether the form exist in the formhosts. + * + * @param formId The Id of the form. + * @return Returns true if contains form; returns false otherwise. + */ +bool FormHostClient::ContainsForm(int64_t formId) +{ + APP_LOGI("%{public}s called.", __func__); + + std::lock_guard lock(lockMutex_); + for (auto recordHostForm : recordHostForms_) { + if (recordHostForm.second.Contains(formId)) { + return true; + } + } + return false; +} + +/** + * @brief Request to give back a form. + * + * @param formJsInfo Form js info. + * @return none. + */ +void FormHostClient::OnAcquired(const FormJsInfo &formJsInfo) +{ + APP_LOGI("%{public}s called.", __func__); + int64_t formId = formJsInfo.formId; + if (formId < 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); + return; + } + std::shared_ptr targetCallback = FindTargetCallback(formId); + if (targetCallback == nullptr) { + APP_LOGE("%{public}s error, can't find target callback. formId: %{public}lld.", __func__, formId); + return; + } + APP_LOGI("%{public}s, formId: %{public}lld, data: %{public}s", __func__, formId, formJsInfo.formData.c_str()); + targetCallback->ProcessFormUpdate(formJsInfo); +} + +/** + * @brief Update form. + * + * @param formJsInfo Form js info. + * @return none. + */ +void FormHostClient::OnUpdate(const FormJsInfo &formJsInfo) +{ + APP_LOGI("%{public}s called.", __func__); + int64_t formId = formJsInfo.formId; + if (formId < 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); + return; + } + std::shared_ptr targetCallback = FindTargetCallback(formId); + if (targetCallback == nullptr) { + APP_LOGE("%{public}s error, can't find target callback. formId: %{public}lld.", __func__, formId); + return; + } + targetCallback->ProcessFormUpdate(formJsInfo); +} + +/** + * @brief UnInstall the forms. + * + * @param formIds The Id of the forms. + * @return none. + */ +void FormHostClient::OnUninstall(const std::vector &formIds) +{ + APP_LOGI("%{public}s called.", __func__); + if (formIds.size() <= 0) { + APP_LOGE("%{public}s error, formIds is empty.", __func__); + return; + } + for(auto &formId : formIds) { + if (formId < 0) { + APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); + continue; + } + std::shared_ptr targetCallback = FindTargetCallback(formId); + if (targetCallback == nullptr) { + APP_LOGE("%{public}s error, can't find target callback. formId: %{public}lld.", __func__, formId); + continue; + } + targetCallback->ProcessFormUninstall(formId); + } +} + +/** + * @brief Find callback by formId. + * + * @param formId The Id of the form. + * @return target callback + */ +std::shared_ptr FormHostClient::FindTargetCallback(int64_t formId) +{ + std::lock_guard lock(lockMutex_); + for (auto record : recordHostForms_) { + if (record.second.Contains(formId)) { + return recordCallback_[record.first]; + } + } + return nullptr; +} + +/** + * @brief Find Key By form callback. + * + * @param formCallback The form callback. + * @return callback's key + */ +int32_t FormHostClient::FindKeyByCallback(std::shared_ptr formCallback) +{ + for (auto recordCallback : recordCallback_) { + if (Compare(recordCallback.second, formCallback)) { + return recordCallback.first; + } + } + return -1; +} + +/** + * @brief Compare form callback. + * + * @param formCallback1 The form callback. + * @param formCallback2 The form callback to be compared with form callback1. + * @return Returns true if the two form callback are equal to each other, returns false otherwise. + */ +bool FormHostClient::Compare(std::shared_ptr formCallback1, + std::shared_ptr formCallback2) +{ + return (formCallback1 == formCallback2) ? true : false; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/fmskit/native/src/form_mgr.cpp b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6531c5afe7dec6ecf8a7e44ecf98b5aad293aabc --- /dev/null +++ b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp @@ -0,0 +1,488 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_mgr.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +FormMgr::FormMgr(){} +FormMgr::~FormMgr() +{ + if (remoteProxy_ != nullptr) { + auto remoteObject = remoteProxy_->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + } +} +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) +{ + APP_LOGI("%{public}s called.", __func__); + + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->AddForm(formId, want, callerToken, formInfo); +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->DeleteForm(formId, callerToken); +} + +/** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + APP_LOGI("%{public}s called.", __func__); + + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->ReleaseForm(formId, callerToken, delCache); +} + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formBindingData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::UpdateForm(const int64_t formId, const std::string &bundleName, const FormProviderData &formBindingData) +{ + APP_LOGI("%{public}s called.", __func__); + + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + // update form + return remoteProxy_->UpdateForm(formId, bundleName, formBindingData); +} + +/** + * @brief Notify the form service that the form user's lifecycle is updated. + * + * This should be called when form user request form. + * + * @param formId Indicates the unique id of form. + * @param callerToken Indicates the callback remote object of specified form user. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ +int FormMgr::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->RequestForm(formId, callerToken, want); +} + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, +const int32_t formVisibleType) +{ + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); +} + +/** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return None. + */ +int FormMgr::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->CastTempForm(formId, callerToken); +} + +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DumpStorageFormInfos(std::string &formInfos) +{ + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->DumpStorageFormInfos(formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DumpFormInfoByBundleName(const std::string bundleName, std::string &formInfos) +{ + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->DumpFormInfoByBundleName(bundleName, formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) +{ + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->DumpFormInfoByFormId(formId, formInfo); +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgr::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->MessageEvent(formId, want, callerToken); +} + +/** + * @brief Set Next Refresh Time. + * @param formId The id of the form. + * @param bundleName The bundle name of form provider. + * @param nextTime Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->SetNextRefreshTime(formId, nextTime); +} + +/** + * @brief Lifecycle Update. + * @param formIds The id of the forms. + * @param callerToken Host client. + * @param updateType Next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgr::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, +const int32_t updateType) +{ + int errCode = Connect(); + if (errCode != ERR_OK) { + return errCode; + } + + return remoteProxy_->LifecycleUpdate(formIds, callerToken, updateType); +} +/** + * @brief Get fms recoverStatus. + * + * @return The current recover status. + */ +int FormMgr::GetRecoverStatus() +{ + APP_LOGI("%{public}s called.", __func__); + + return recoverStatus_; +} + +/** + * @brief Set fms recoverStatus. + * + * @param recoverStatus The recover status. + */ +void FormMgr::SetRecoverStatus(int recoverStatus) +{ + APP_LOGI("%{public}s called.", __func__); + + recoverStatus_ = recoverStatus; +} + +/** + * @brief Register death callback. + * + * @param deathCallback Death callback. + */ +void FormMgr::RegisterDeathCallback(const std::shared_ptr &formDeathCallback) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formDeathCallback == nullptr) { + APP_LOGE("%{public}s error, form death callback is nullptr.", __func__); + return; + } + + formDeathCallbacks_.emplace_back(formDeathCallback); +} + +/** + * @brief UnRegister death callback. + * + * @param deathCallback Death callback. + */ +void FormMgr::UnRegisterDeathCallback(const std::shared_ptr &formDeathCallback) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formDeathCallback == nullptr) { + APP_LOGE("%{public}s error, form death callback is nullptr.", __func__); + return; + } + + // Remove the specified death callback in the vector of death callback + auto iter = std::find(formDeathCallbacks_.begin(), formDeathCallbacks_.end(), formDeathCallback); + if (iter != formDeathCallbacks_.end()) { + formDeathCallbacks_.erase(iter); + } + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Get death recipient. + * @return deathRecipient_. + */ +sptr FormMgr::GetDeathRecipient() const +{ + return deathRecipient_; +} + +/** + * @brief Check whether the specified death callback is registered in form mgr. + * @param formDeathCallback The specified death callback for checking. + * @return Return true on success, false on failure. + */ +bool FormMgr::CheckIsDeathCallbackRegistered(const std::shared_ptr &formDeathCallback) +{ + APP_LOGI("%{public}s called.", __func__); + + auto iter = std::find(formDeathCallbacks_.begin(), formDeathCallbacks_.end(), formDeathCallback); + if (iter != formDeathCallbacks_.end()) { + return true; + } + + return false; +} + +/** + * @brief Notices IRemoteBroker died. + * @param remote remote object. + */ +void FormMgr::FormMgrDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGI("%{public}s called.", __func__); + + if (remote == nullptr) { + APP_LOGE("%{public}s failed, remote is nullptr.", __func__); + return; + } + + if (FormMgr::GetInstance().GetRecoverStatus() == Constants::IN_RECOVERING) { + APP_LOGW("%{public}s, fms in recovering.", __func__); + return; + } + // Reset proxy + FormMgr::GetInstance().ResetProxy(remote); + + if (!FormMgr::GetInstance().Reconnect()) { + APP_LOGE("%{public}s, form mgr service died, try to reconnect to fms failed.", __func__); + FormMgr::GetInstance().SetRecoverStatus(Constants::RECOVER_FAIL); + return; + } + + // refresh form host. + for (auto &deathCallback : FormMgr::GetInstance().formDeathCallbacks_) { + deathCallback->OnDeathReceived(); + } + FormMgr::GetInstance().SetRecoverStatus(Constants::NOT_IN_RECOVERY); +} + +/** + * @brief Reconnect form manager service once per 1000 milliseconds, + * until the connection succeeds or reaching the max retry times. + * @return Returns true if execute success, false otherwise. + */ +bool FormMgr::Reconnect() +{ + APP_LOGI("%{public}s called.", __func__); + + for (int i = 0; i < Constants::MAX_RETRY_TIME; i++) { + // Sleep 1000 milliseconds before reconnect. + std::this_thread::sleep_for(std::chrono::milliseconds(Constants::SLEEP_TIME)); + + // try to connect fms + if (Connect() != ERR_OK) { + APP_LOGE("%{public}s, get fms proxy fail, try again.", __func__); + continue; + } + + APP_LOGI("%{public}s, get fms proxy success.", __func__); + return true; + } + + return false; +} + +/** + * @brief Connect form manager service. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgr::Connect() +{ + std::lock_guard lock(connectMutex_); + if (remoteProxy_ != nullptr && !resetFlag_) { + return ERR_OK; + } + + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + APP_LOGE("%{private}s:fail to get registry", __func__); + return ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED; + } + sptr remoteObject = systemManager->GetSystemAbility(FORM_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + APP_LOGE("%{private}s:fail to connect FormMgrService", __func__); + return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; + } + deathRecipient_ = sptr(new FormMgrDeathRecipient()); + if (deathRecipient_ == nullptr) { + APP_LOGE("%{public}s :Failed to create FormMgrDeathRecipient!", __func__); + return ERR_NO_MEMORY; + } + if ((remoteObject->IsProxyObject()) && (!remoteObject->AddDeathRecipient(deathRecipient_))) { + APP_LOGE("%{public}s :Add death recipient to FormMgrService failed.", __func__); + return ERR_APPEXECFWK_FORM_ADD_DEATH_RECIPIENT_FAILED; + } + + remoteProxy_ = iface_cast(remoteObject); + APP_LOGD("%{public}s :Connecting FormMgrService success.", __func__); + return ERR_OK; +} + +/** + * @brief Reset proxy. + * @param remote remote object. + */ +void FormMgr::ResetProxy(const wptr &remote) +{ + APP_LOGI("%{public}s called.", __func__); + + std::lock_guard lock(connectMutex_); + if (remoteProxy_ == nullptr) { + APP_LOGE("%{public}s failed, remote proxy is nullptr.", __func__); + return; + } + + // set formMgr's recover status to IN_RECOVERING. + recoverStatus_ = Constants::IN_RECOVERING; + + // remove the death recipient + auto serviceRemote = remoteProxy_->AsObject(); + if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) { + serviceRemote->RemoveDeathRecipient(deathRecipient_); + } + // clearn the remote proxy + remoteProxy_ = nullptr; +} + +/** + * @brief Set form mgr service for test. + */ +void FormMgr::SetFormMgrService(sptr formMgrService) +{ + APP_LOGI("%{public}s called.", __func__); + remoteProxy_ = formMgrService; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/blocking_queue.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/blocking_queue.h index 64d9111fd2867faa1cb7ef6f0e1c5a006033a7cd..74d6605ba8c0d23c9d08d8736445f68fde1bb937 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/blocking_queue.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/blocking_queue.h @@ -80,7 +80,7 @@ public: { std::unique_lock lock(mutex_); while (queue_.empty() && !stopFlag_) { - APP_LOGD("BlockingQueue::Take empty_wait"); + APP_LOGI("BlockingQueue::Take empty_wait"); empty_.wait(lock); } @@ -98,7 +98,7 @@ public: std::unique_lock lock(mutex_); while (queue_.empty() && !stopFlag_) { if (empty_.wait_until(lock, timeout) == std::cv_status::timeout) { - APP_LOGD("BlockingQueue::Poll timeout"); + APP_LOGI("BlockingQueue::Poll timeout"); break; } } diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/global_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/global_task_dispatcher.h index 20706e4112d2e4ae7333dcb62347baa776499b70..01479ebc4a78c59a8effb6b65e9caa24bb33edd8 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/global_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/global_task_dispatcher.h @@ -24,8 +24,6 @@ namespace OHOS { namespace AppExecFwk { /** * Dispatcher for global thread model. - * - * */ class GlobalTaskDispatcher : public ParallelTaskDispatcherBase { private: diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher.h index 09673a88cd75271e2e57013eba0ddf1ea48e84a9..57e9a5598ee1a2cce447bca9e5c625262b932ec8 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher.h @@ -32,13 +32,9 @@ namespace OHOS { namespace AppExecFwk { /** * Customed parallel TaskDispatcher which means it can be created multi times. - * - * */ class ParallelTaskDispatcher : public ParallelTaskDispatcherBase { public: - // ParallelTaskDispatcher(); - ParallelTaskDispatcher(const std::string &name, TaskPriority priority, std::shared_ptr &executor); ~ParallelTaskDispatcher(){}; diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher_base.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher_base.h index 8eac6d8887ffeca87eb252ef3499fc433ba544d2..22b248f0dfcaca62b97d5c5a04d449fef8b6453e 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher_base.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/parallel_task_dispatcher_base.h @@ -35,14 +35,10 @@ namespace OHOS { namespace AppExecFwk { /** * Base implementation for parallel TaskDispatcher - * - * */ class ParallelTaskDispatcherBase : public BaseTaskDispatcher, public std::enable_shared_from_this { public: - // ParallelTaskDispatcherBase(); - ParallelTaskDispatcherBase( TaskPriority taskPriority, std::shared_ptr &executor, const std::string &dispatcherName); virtual ~ParallelTaskDispatcherBase() = default; @@ -108,7 +104,7 @@ private: void OnChanged(const TaskStage &stage) { if (stage.IsDone()) { - APP_LOGD("task done."); + APP_LOGI("ParallelTaskDispatcherBase task done."); callback_(); } } diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h index ef51a1f030c66c07bc0ddc0758fe8444190b7a50..9388e9ce0c9619f08469b99a27133732320d5f23 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h @@ -33,8 +33,6 @@ namespace AppExecFwk { /** * Dispatcher for serial thread model. - * - * */ class SerialTaskDispatcher : public BaseTaskDispatcher, public std::enable_shared_from_this { private: @@ -123,7 +121,7 @@ public: /** * Called when post a task group to the TaskDispatcher and without waiting * - * @param runnable is the job to execute + * @param runnable is the job to execute * @param delayMs indicate the delay time to execute * @return an interface for revoke the task if it hasn't been invoked. * diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_task_dispatcher.h index b3f5a2267651570b627321dbf0d001081d6ab634..8052d0d6b6a77022caad09fb66acf3d0021cb8d6 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_task_dispatcher.h @@ -29,18 +29,13 @@ namespace OHOS { namespace AppExecFwk { class EventRunner; -/** - * Dispatcher for specific thread model like UI / Main / IO and so on. - * - * - */ class SpecTaskDispatcher : public BaseTaskDispatcher, public std::enable_shared_from_this { public: /** * constructor for special task dispatchers * * @param config which is the config of this dispatcher - * @param looper task looper + * @param runner event runner * */ SpecTaskDispatcher(std::shared_ptr config, std::shared_ptr runner); @@ -50,7 +45,7 @@ public: * Called when post a task to the TaskDispatcher with waiting Attention: Call * this function of Specific dispatcher on the corresponding thread will lock. * - * @param task is the job to execute + * @param runnable is the job to execute * */ ErrCode SyncDispatch(const std::shared_ptr &runnable); @@ -58,7 +53,7 @@ public: /** * Called when post a task to the TaskDispatcher without waiting * - * @param task is the job to execute + * @param runnable is the job to execute * @return an interface for revoke the task if it hasn't been invoked. * */ @@ -67,7 +62,7 @@ public: /** * Called when post a task group to the TaskDispatcher and without waiting * - * @param task is the job to execute + * @param runnable is the job to execute * @param delayMs indicate the delay time in milliseconds to execute * @return an interface for revoke the task if it hasn't been invoked. * diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/task_dispatcher_context.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/task_dispatcher_context.h index 0d8ee8edd880e5c1b99dcf17a74e4358dc38294c..c7516d2b1fe5ea66eba55b02b82269610036e0bc 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/task_dispatcher_context.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/task_dispatcher_context.h @@ -34,8 +34,6 @@ namespace OHOS { namespace AppExecFwk { /** * Dispatcher management for all kinds dispatchers and executor. - * - * */ class TaskDispatcherContext { public: diff --git a/interfaces/innerkits/task_dispatcher/include/task/barrier_handler.h b/interfaces/innerkits/task_dispatcher/include/task/barrier_handler.h index 89bb5cdf2a809aba3408c60ad2a93f5caf9b5b37..a8f5d070aad3da39b623307b73b5d0bc95a3716a 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/barrier_handler.h +++ b/interfaces/innerkits/task_dispatcher/include/task/barrier_handler.h @@ -68,7 +68,7 @@ private: void OnChanged(const TaskStage &stage) { if (stage.IsDone()) { - APP_LOGI("task done."); + APP_LOGI("BarrierHandler task done."); callback_(); } }; diff --git a/interfaces/innerkits/task_dispatcher/include/task/sync_task.h b/interfaces/innerkits/task_dispatcher/include/task/sync_task.h index 6c2cca11bdd1c1f3f59b081e15ec9cf21251e9d2..7a53ff822292c2726e19f7f49e968dd3ba679904 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/sync_task.h +++ b/interfaces/innerkits/task_dispatcher/include/task/sync_task.h @@ -34,27 +34,11 @@ namespace AppExecFwk { class SyncTask final : public Task { public: - /** - *@brief Constructs the object. - *@param runnable The task. - *@param priority The priority - *@return - - */ SyncTask(const std::shared_ptr &runnable, TaskPriority priority, const std::shared_ptr &baseTaskDispatcher); - /** - *@brief invoke the function to execute the task - *@param - - *@return void - */ void Run() override; - /** - *@brief wait the task to run completely - *@param - - *@return void - */ void WaitTask(); private: diff --git a/interfaces/innerkits/task_dispatcher/include/task/task.h b/interfaces/innerkits/task_dispatcher/include/task/task.h index caa5df0b749c22832aceb4935fbfd5912878d340..82a5c0d4a8877941b57c8d13ee87dfd5c64d604f 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task.h @@ -31,12 +31,6 @@ namespace AppExecFwk { class BaseTaskDispatcher; class Task : public Revocable { public: - /** - * @brief Constructs the object. - * @param runnable The user task wrapped in. - * @param priority The priority - * @return - - */ Task(const std::shared_ptr &runnable, const TaskPriority priority, const std::shared_ptr &baseTaskDispatcher); @@ -44,36 +38,29 @@ public: /** *@brief invoke the function to execute the task - *@param - - *@return void */ virtual void Run(); /** * @brief Gets the priority. - * @param - * @return The priority. */ TaskPriority GetPriority() const; /** * @brief Sets the sequence. - * @param - * @param sequence The sequence - * @return void */ void SetSequence(long sequence); /** *@brief Gets the sequence. - *@param - *@return The sequence. */ long GetSequence() const; /** *@brief Revoke this task if hasn't run. - *@param - *@return true if set revoked or already revoked. False if the task has start executing. */ bool Revoke() override; @@ -81,44 +68,27 @@ public: /** *@brief Adds a task listener. *@param listener The listener - *@return void */ void AddTaskListener(const std::shared_ptr &listener); /** *@brief Called when task is about to run. - *@param - - *@return void */ void BeforeTaskExecute(); /** *@brief Called when task is done. - *@param - - *@return void */ void AfterTaskExecute(); /** *@brief Called when task is canceled. - *@param - - *@return void */ void OnTaskCanceled(); - /** - *@brief Save traceId for using on task running thread. - *@param hiTraceId The traceId. - *@return void - */ - // void SetTaskHiTraceId(HiTraceId &hiTraceId); - bool operator==(std::shared_ptr &rec) const; protected: - /** - * The user task wrapped in. - */ std::shared_ptr runnable_; private: @@ -143,10 +113,10 @@ private: void ConcurrentQueueStatusUpdate(const TaskStage::TASKSTAGE taskstage); private: - const static int EXECUTED = (1 << 0); - const static int REVOKED = (1 << 1); - long sequence_; - std::atomic state_; + const static unsigned int EXECUTED = (1 << 0); + const static unsigned int REVOKED = (1 << 1); + long sequence_ = 0; + std::atomic state_; TaskPriority priority_; std::shared_ptr revocable_ = nullptr; ConcurrentQueue> taskListeners_; diff --git a/interfaces/innerkits/task_dispatcher/include/task/task_handler_libevent_adapter.h b/interfaces/innerkits/task_dispatcher/include/task/task_handler_libevent_adapter.h index 9105aa34a14d8f8f0f1e73375ed093b772b3ba2f..732b5e17a4126c8f394684f6aea16cf7a98738d8 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task_handler_libevent_adapter.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task_handler_libevent_adapter.h @@ -24,28 +24,24 @@ #include "event_queue.h" namespace OHOS { namespace AppExecFwk { - -/** - * Dispatcher for serial thread model. - * - * - */ class TaskHandlerLibeventAdapter final : public EventHandler, public TaskDispatcherHandler { public: - TaskHandlerLibeventAdapter(const std::shared_ptr &eventRunner) : EventHandler(eventRunner) - {} + TaskHandlerLibeventAdapter(const std::shared_ptr &eventRunner) : EventHandler(eventRunner){}; virtual ~TaskHandlerLibeventAdapter(){}; bool Dispatch(const std::shared_ptr &runnable) override { + APP_LOGI("TaskHandlerLibeventAdapter::Dispatch called."); return EventHandler::PostTask(*(runnable.get()), EventQueue::Priority::HIGH); } bool Dispatch(const std::shared_ptr &runnable, long delayMs) override { + APP_LOGI("TaskHandlerLibeventAdapter::Delay Dispatch called."); return EventHandler::PostTask(*(runnable.get()), delayMs, EventQueue::Priority::HIGH); } bool DispatchSync(const std::shared_ptr &runnable) override { + APP_LOGI("TaskHandlerLibeventAdapter::Delay Dispatch Sync called."); return EventHandler::PostSyncTask(*(runnable.get()), EventQueue::Priority::HIGH); } }; diff --git a/interfaces/innerkits/task_dispatcher/include/task/task_stage.h b/interfaces/innerkits/task_dispatcher/include/task/task_stage.h index 00678029d0d49e79432782d4048a2cb00c631d6a..d7c678dcd89462eabd7b3c36751ce245abcc5091 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task_stage.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task_stage.h @@ -17,11 +17,6 @@ namespace OHOS { namespace AppExecFwk { -/** - * Enumeration for task execute stage. - * Attention: |REVOKED| is conflict with |AFTER_EXECUTE| and |BEFORE_EXECUTE|, which means, - * once |REVOKED|, the other stage will not be notified. So use |isDone| for judging. - */ class TaskStage { public: TaskStage() : index_(0) @@ -30,7 +25,11 @@ public: { index_ = index; } - + /** + * Enumeration for task execute stage. + * Attention: |REVOKED| is conflict with |AFTER_EXECUTE| and |BEFORE_EXECUTE|, which means, + * once |REVOKED|, the other stage will not be notified. So use |isDone| for judging. + */ enum TASKSTAGE { BEFORE_EXECUTE = 0, AFTER_EXECUTE = 1, REVOKED = 2 }; /** * Gets the index. diff --git a/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h b/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h index ee26ee8a758c2fbf2f2b43161e46ef04c280c8a3..1885cddd81b2ac6574861f0020eb1d7ea256d442 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h @@ -27,8 +27,7 @@ namespace AppExecFwk { template class ConcurrentQueue { public: - ConcurrentQueue() : empty_() - {} + ConcurrentQueue() : empty_(){}; /** * get data without block @@ -52,7 +51,7 @@ public: { std::unique_lock lock(mutex_); while (queue_.empty()) { - APP_LOGD("ConcurrentQueue::Take blocked"); + APP_LOGI("ConcurrentQueue::Take blocked"); empty_.wait(lock); } @@ -64,7 +63,7 @@ public: { std::unique_lock lock(mutex_); if (queue_.empty()) { - APP_LOGD("ConcurrentQueue::Poll empty"); + APP_LOGI("ConcurrentQueue::Poll empty"); return nullptr; } T front(queue_.front()); diff --git a/interfaces/innerkits/task_dispatcher/include/threading/delay_queue.h b/interfaces/innerkits/task_dispatcher/include/threading/delay_queue.h index 3726faf8b7772715890134dd14fc350f4122f5a3..49b72d4a5e98273c06b1b97379e2a5cabb00c403 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/delay_queue.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/delay_queue.h @@ -65,11 +65,12 @@ public: while (true) { std::unique_lock lock(mutex_); while (taskQueue_.empty() && !stopFlag_) { - APP_LOGD("DelayQueue::taskQueue_ is empty"); + APP_LOGI("DelayQueue::taskQueue_ is empty"); emptyWait_.wait(lock); } if (taskQueue_.empty() && stopFlag_) { + APP_LOGI("DelayQueue::taskQueue is empty and stopFlag is true"); return nullptr; } diff --git a/interfaces/innerkits/task_dispatcher/include/threading/thread_factory.h b/interfaces/innerkits/task_dispatcher/include/threading/thread_factory.h index 3b3985edbdf2d275ceb4defaa94b68f7afacfa0c..ff2e777983d00e35a99fd3fad0f02b8289893ea9 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/thread_factory.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/thread_factory.h @@ -37,8 +37,6 @@ public: /** * ThreadFactory is an interface for producing thread. - * - * */ class ThreadFactory { public: diff --git a/interfaces/innerkits/task_dispatcher/include/threading/work_thread.h b/interfaces/innerkits/task_dispatcher/include/threading/work_thread.h index e62d98dd8c75c10e1a049a8088ea6bdabe2ecda1..ebdbf2008584a214fcf9a62ab92709d8a07d5680 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/work_thread.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/work_thread.h @@ -29,7 +29,6 @@ namespace AppExecFwk { class WorkerThread; /** * Interface for a work delegate. - * */ class Delegate { public: @@ -44,7 +43,6 @@ public: /** * WorkerThread is a thread with a loop which can execute incoming tasks. - * */ class WorkerThread : public std::enable_shared_from_this { public: diff --git a/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h b/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h index 0377427ea12473d943262d91ada9f93cbc6abf02..edf8a97adc088c81bcae6b0da232cf41d16ee3af 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h @@ -76,15 +76,15 @@ private: void InterruptWorkers(void); - static int GetWorkingThreadNum(int ctl); + static unsigned int GetWorkingThreadNum(unsigned int ctl); static bool IsRunning(int ctl); static int GetStateFromControl(int ctl); - static int CombineToControl(int state, int count); + static int CombineToControl(unsigned int state, unsigned int count); - void AdvanceStateTo(int target); + void AdvanceStateTo(unsigned int target); bool CompareAndIncThreadNum(int expect); @@ -97,7 +97,7 @@ private: static const int MAX_THREAD_LOWER_LIMIT; static const int CORE_THREAD_LOWER_LIMIT; static const int COUNT_BITS; - static const int CAPACITY; + static const unsigned int CAPACITY; static const int RUNNING; static const int CLOSING; static const int INTERRUPT; diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp index 6a0dc0171e644ec14acb799664da323db0360bc2..d007d4aa03e142e74037df6adad919547d55c79d 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/base_task_dispatcher.cpp @@ -31,30 +31,37 @@ BaseTaskDispatcher::BaseTaskDispatcher(const std::string &dispatcherName, const ErrCode BaseTaskDispatcher::SyncDispatchBarrier(const std::shared_ptr &task) { + APP_LOGI("BaseTaskDispatcher::SyncDispatchBarrier called"); return SyncDispatch(task); } ErrCode BaseTaskDispatcher::AsyncDispatchBarrier(const std::shared_ptr &task) { + APP_LOGI("BaseTaskDispatcher::AsyncDispatchBarrier start"); std::shared_ptr revocable = AsyncDispatch(task); if (revocable != nullptr) { + APP_LOGI("BaseTaskDispatcher::AsyncDispatchBarrier end"); return ERR_OK; } + APP_LOGE("BaseTaskDispatcher::AsyncDispatchBarrier revocable is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; } std::shared_ptr BaseTaskDispatcher::CreateDispatchGroup() { + APP_LOGI("BaseTaskDispatcher::CreateDispatchGroup called."); return std::make_shared(); } std::shared_ptr BaseTaskDispatcher::AsyncGroupDispatch( const std::shared_ptr &group, const std::shared_ptr &task) { + APP_LOGI("BaseTaskDispatcher::AsyncGroupDispatch called."); return AsyncDispatch(task); } bool BaseTaskDispatcher::GroupDispatchWait(const std::shared_ptr &group, long timeout) { + APP_LOGI("BaseTaskDispatcher::GroupDispatchWait start"); if (group == nullptr) { APP_LOGE("BaseTaskDispatcher::GroupDispatchWait group is nullptr"); return false; @@ -64,58 +71,60 @@ bool BaseTaskDispatcher::GroupDispatchWait(const std::shared_ptr &group, APP_LOGE("BaseTaskDispatcher::GroupDispatchWait groupImpl is nullptr"); return false; } - return groupImpl->AwaitAllTasks(timeout); + bool result = groupImpl->AwaitAllTasks(timeout); + APP_LOGI("BaseTaskDispatcher::GroupDispatchWait start"); + return result; } ErrCode BaseTaskDispatcher::GroupDispatchNotify( const std::shared_ptr &group, const std::shared_ptr &task) { - bool flag = true; + APP_LOGI("BaseTaskDispatcher::GroupDispatchNotify start"); if (group == nullptr) { - APP_LOGE("group cannot be null."); - flag = false; + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify group cannot be null."); + return ERR_APPEXECFWK_CHECK_FAILED; } if (task == nullptr) { - APP_LOGE("task cannot be null"); - flag = false; + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify task cannot be null"); + return ERR_APPEXECFWK_CHECK_FAILED; } const std::function asyncDispatch = std::bind(&BaseTaskDispatcher::AsyncDispatch, this, task); if (asyncDispatch == nullptr) { APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify asyncDispatch is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; } std::shared_ptr ptrCallback = std::make_shared(asyncDispatch); if (ptrCallback == nullptr) { APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify runnable is nullptr"); - flag = false; + return ERR_APPEXECFWK_CHECK_FAILED; } if (group == nullptr) { APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify group is nullptr"); - flag = false; + return ERR_APPEXECFWK_CHECK_FAILED; } std::shared_ptr groupImpl = CastToGroupImpl(group); if (groupImpl == nullptr) { APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify groupImpl is nullptr"); - flag = false; - } - if (!flag) { return ERR_APPEXECFWK_CHECK_FAILED; } - if (groupImpl->AddNotification(ptrCallback)) { + APP_LOGI("BaseTaskDispatcher::GroupDispatchNotify end"); return ERR_OK; }; + APP_LOGE("BaseTaskDispatcher::GroupDispatchNotify addNotification failed"); return ERR_APPEXECFWK_CHECK_FAILED; } ErrCode BaseTaskDispatcher::ApplyDispatch(const std::shared_ptr> &task, long iterations) { + APP_LOGI("BaseTaskDispatcher::ApplyDispatch start"); if (task == nullptr) { - APP_LOGE("task object is not set"); + APP_LOGE("BaseTaskDispatcher::ApplyDispatch task object is not set"); return ERR_APPEXECFWK_CHECK_FAILED; } if (iterations <= 0) { - APP_LOGE("iterations must giant than 0"); + APP_LOGE("BaseTaskDispatcher::ApplyDispatch iterations must giant than 0"); return ERR_APPEXECFWK_CHECK_FAILED; } @@ -128,18 +137,21 @@ ErrCode BaseTaskDispatcher::ApplyDispatch(const std::shared_ptr revocable = AsyncDispatch(ptrCallback); if (revocable == nullptr) { - APP_LOGE("BaseTaskDispatcher::ApplyDispatch revocable is nullptr"); + APP_LOGE("BaseTaskDispatcher::ApplyDispatch revocable is nullptr, index:%{public}ld", i); flag = false; } } if (flag) { + APP_LOGI("BaseTaskDispatcher::ApplyDispatch end"); return ERR_OK; } + APP_LOGI("BaseTaskDispatcher::ApplyDispatch failed"); return ERR_APPEXECFWK_CHECK_FAILED; } ErrCode BaseTaskDispatcher::Check(const std::shared_ptr &task) const { + APP_LOGI("BaseTaskDispatcher::Check called"); if (task == nullptr) { APP_LOGE("dispatch task cannot be null."); return ERR_APPEXECFWK_CHECK_FAILED; @@ -149,6 +161,7 @@ ErrCode BaseTaskDispatcher::Check(const std::shared_ptr &task) const std::shared_ptr BaseTaskDispatcher::CastToGroupImpl(const std::shared_ptr &group) { + APP_LOGI("BaseTaskDispatcher::CastToGroupImpl called"); std::shared_ptr groupImpl_ptr = std::static_pointer_cast(group); if (groupImpl_ptr != nullptr) { return groupImpl_ptr; @@ -170,14 +183,15 @@ TaskPriority BaseTaskDispatcher::GetPriority() const void BaseTaskDispatcher::TracePointBeforePost( std::shared_ptr &task, bool isAsyncTask, const std::string &dispatcherName) const { - + APP_LOGI("BaseTaskDispatcher::TracePointBeforePost called"); if (task == nullptr) { - APP_LOGE("tracePointBeforePost the task is null"); + APP_LOGE("BaseTaskDispatcher::TracePointBeforePost the task is nullptr"); return; } std::string taskType = isAsyncTask ? "ASYNC_TASK_STRING" : "SYNC_TASK_STRING"; long seq = task->GetSequence(); - APP_LOGD("tracePointBeforePost log---TaskType:%{public}s,TaskSeq::%{public}ld,DispatcherName::%{public}s", + APP_LOGI("BaseTaskDispatcher::TracePointBeforePost " + "log---TaskType:%{public}s,TaskSeq:%{public}ld,DispatcherName::%{public}s", taskType.c_str(), seq, dispatcherName.c_str()); @@ -186,13 +200,15 @@ void BaseTaskDispatcher::TracePointBeforePost( void BaseTaskDispatcher::TracePointAfterPost( std::shared_ptr &task, bool isAsyncTask, const std::string &dispatcherName) const { + APP_LOGI("BaseTaskDispatcher::TracePointAfterPost called"); if (task == nullptr) { - APP_LOGE("TracePointAfterPost the task is null"); + APP_LOGE("BaseTaskDispatcher::TracePointAfterPost the task is nullptr"); return; } std::string taskType = isAsyncTask ? "ASYNC_TASK_STRING" : "SYNC_TASK_STRING"; long seq = task->GetSequence(); - APP_LOGD("tracePointBeforePost log---TaskType:%{public}s,TaskSeq::%{public}ld,DispatcherName::%{public}s", + APP_LOGI("BaseTaskDispatcher::TracePointAfterPost " + "log---TaskType:%{public}s,TaskSeq:%{public}ld,DispatcherName::%{public}s", taskType.c_str(), seq, dispatcherName.c_str()); diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp index d44df5bace3cc5d3009aeb11134b0c99be1d8d0f..ed3b982aca4b115e217a776d030c419018657b6f 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp @@ -30,11 +30,13 @@ GroupImpl::GroupImpl() */ bool GroupImpl::AwaitAllTasks(long timeout) { + APP_LOGI("GroupImpl::AwaitAllTasks start"); if (count_.load() == 0) { - APP_LOGD("GroupImpl::AwaitAllTasks number of count_ is zero"); + APP_LOGI("GroupImpl::AwaitAllTasks number of count_ is zero"); return true; } if (timeout <= 0L) { + APP_LOGW("GroupImpl::AwaitAllTasks timeout<=0"); return false; } bool success = true; @@ -42,34 +44,31 @@ bool GroupImpl::AwaitAllTasks(long timeout) while (count_.load() > 0) { if (condition_.wait_for(lock, std::chrono::milliseconds(timeout)) == std::cv_status::timeout) { success = false; - APP_LOGD("GroupImpl::awaitAllTasks timeout"); + APP_LOGI("GroupImpl::awaitAllTasks timeout"); break; } - APP_LOGD("GroupImpl::awaitAllTasks success"); + APP_LOGI("GroupImpl::awaitAllTasks success"); } + APP_LOGI("GroupImpl::AwaitAllTasks end"); return success; } /** - * @brief Associates a task to this group. + * @brief Associates a task to this group. * - * @return None */ void GroupImpl::Associate() { - APP_LOGD("GroupImpl::Associate called add a task"); - // count_++; + APP_LOGI("GroupImpl::Associate called add a task"); count_.fetch_add(1); } /** * @brief Notify group that a task is done or canceled. * - * @return None */ void GroupImpl::NotifyTaskDone() { - APP_LOGD("GroupImpl::NotifyTaskDone called notify a task to complete"); - // int newValue = (--count_); + APP_LOGI("GroupImpl::NotifyTaskDone start. Called notify a task to complete"); count_.fetch_sub(1); int newValue = count_.load(); if (newValue > 0) { @@ -78,6 +77,8 @@ void GroupImpl::NotifyTaskDone() std::unique_lock lock(dataMutex_); condition_.notify_all(); DrainNotifications(); + + APP_LOGI("GroupImpl::NotifyTaskDone end"); } /** * @brief Adds the |notification| to notification list. @@ -86,10 +87,10 @@ void GroupImpl::NotifyTaskDone() * * @param notification Called when all tasks done. * - * @return None */ bool GroupImpl::AddNotification(const std::shared_ptr ¬ification) { + APP_LOGI("GroupImpl::AddNotification start"); if (count_.load() != 0) { std::unique_lock lock(dataMutex_); if (notifications_.size() == MAX_TASK) { @@ -97,30 +98,32 @@ bool GroupImpl::AddNotification(const std::shared_ptr ¬ification) return false; } if (count_.load() != 0) { - APP_LOGD("GroupImpl::AddNotification called add task"); + APP_LOGI("GroupImpl::AddNotification called add task"); notifications_.push_back(notification); return true; } } if (notification) { + APP_LOGI("GroupImpl::AddNotification notification execute"); (*notification)(); } + APP_LOGI("GroupImpl::AddNotification end"); return true; } /** - *@brief Notify all tasks and remove from queue. + * @brief Notify all tasks and remove from queue. * Attention: Notifications added after all tasks done is not guaranteed. - * - * @return None */ void GroupImpl::DrainNotifications() { - APP_LOGD("GroupImpl::DrainNotifications called task execution"); + APP_LOGI("GroupImpl::DrainNotifications start"); while (notifications_.size() > 0) { std::shared_ptr notification = notifications_.front(); notifications_.pop_front(); + APP_LOGI("GroupImpl::DrainNotifications execute notification"); (*notification)(); } + APP_LOGI("GroupImpl::DrainNotifications end"); } } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp index a5514bc1c6801dd3d30aee8db97229c118c0412a..2f417c8d5d3f0c8695c038b13a4a7799d324e246 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher.cpp @@ -34,6 +34,7 @@ std::shared_ptr ParallelTaskDispatcher::GetInterceptor() ErrCode ParallelTaskDispatcher::SyncDispatchBarrier(const std::shared_ptr &runnable) { + APP_LOGI("ParallelTaskDispatcher::SyncDispatchBarrier start"); if (Check(runnable) != ERR_OK) { APP_LOGE("ParallelTaskDispatcher::SyncDispatchBarrier Check failed"); return ERR_APPEXECFWK_CHECK_FAILED; @@ -62,7 +63,9 @@ ErrCode ParallelTaskDispatcher::SyncDispatchBarrier(const std::shared_ptr &runnable) { + APP_LOGI("ParallelTaskDispatcher::AsyncDispatchBarrier start"); if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcher::AsyncDispatchBarrier check failed"); return ERR_APPEXECFWK_CHECK_FAILED; } if (barrierHandler_ == nullptr) { @@ -70,13 +73,14 @@ ErrCode ParallelTaskDispatcher::AsyncDispatchBarrier(const std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); - APP_LOGD("ParallelTaskDispatcher::AsyncDispatchBarrier into new async task"); + APP_LOGI("ParallelTaskDispatcher::AsyncDispatchBarrier into new async task"); if (innerTask == nullptr) { APP_LOGE("ParallelTaskDispatcher::AsyncDispatchBarrier innerTask is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; } barrierHandler_->AddBarrier(innerTask); + APP_LOGI("ParallelTaskDispatcher::AsyncDispatchBarrier end"); return ERR_OK; } diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp index 6e6e64189ddf906e4eefbac8cb3a126522966f0c..de9e3e011b20b3043b639690e0260b189ecf0951 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp @@ -32,6 +32,7 @@ ParallelTaskDispatcherBase::ParallelTaskDispatcherBase( } ErrCode ParallelTaskDispatcherBase::InterceptedExecute(std::shared_ptr &task) { + APP_LOGI("ParallelTaskDispatcherBase::InterceptedExecute start"); if (executor_ == nullptr) { APP_LOGE("ParallelTaskDispatcherBase::InterceptedExecute executor_ is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; @@ -44,11 +45,13 @@ ErrCode ParallelTaskDispatcherBase::InterceptedExecute(std::shared_ptr &ta } executor_->Execute(task); + APP_LOGI("ParallelTaskDispatcherBase::InterceptedExecute end"); return ERR_OK; } ErrCode ParallelTaskDispatcherBase::SyncDispatch(const std::shared_ptr &runnable) { + APP_LOGI("ParallelTaskDispatcherBase::SyncDispatch start"); if (Check(runnable) != ERR_OK) { APP_LOGE("ParallelTaskDispatcherBase::SyncDispatch check failed"); return ERR_APPEXECFWK_CHECK_FAILED; @@ -64,40 +67,45 @@ ErrCode ParallelTaskDispatcherBase::SyncDispatch(const std::shared_ptr APP_LOGE("ParallelTaskDispatcherBase::SyncDispatch innerTask is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; } - APP_LOGD("ParallelTaskDispatcherBase::SyncDispatch into new sync task"); + APP_LOGI("ParallelTaskDispatcherBase::SyncDispatch into new sync task"); ErrCode execute = InterceptedExecute(innerTask); if (execute != ERR_OK) { APP_LOGE("ParallelTaskDispatcherBase::SyncDispatch execute failed"); return execute; } innerSyncTask->WaitTask(); - APP_LOGD("ParallelTaskDispatcherBase::SyncDispatch end"); + APP_LOGI("ParallelTaskDispatcherBase::SyncDispatch end"); return ERR_OK; } std::shared_ptr ParallelTaskDispatcherBase::AsyncDispatch(const std::shared_ptr &runnable) { + APP_LOGI("ParallelTaskDispatcherBase::AsyncDispatch start"); if (Check(runnable) != ERR_OK) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncDispatch check failed."); return nullptr; } std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::AsyncDispatch innerTask is nullptr."); return nullptr; } TracePointBeforePost(innerTask, true, ASYNC_DISPATCHER_TAG); - APP_LOGD("ParallelTaskDispatcherBase::AsyncDispatch into new async task"); + APP_LOGI("ParallelTaskDispatcherBase::AsyncDispatch into new async task"); ErrCode execute = InterceptedExecute(innerTask); if (execute != ERR_OK) { APP_LOGE("ParallelTaskDispatcherBase::AsyncDispatch execute failed"); return nullptr; } + APP_LOGI("ParallelTaskDispatcherBase::AsyncDispatch end"); return innerTask; } std::shared_ptr ParallelTaskDispatcherBase::DelayDispatch( const std::shared_ptr &runnable, long delayMs) { + APP_LOGI("ParallelTaskDispatcherBase::DelayDispatch start"); if (Check(runnable) != ERR_OK) { APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch Check failed"); return nullptr; @@ -110,6 +118,7 @@ std::shared_ptr ParallelTaskDispatcherBase::DelayDispatch( std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); if (innerTask == nullptr) { + APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch innerTask is nullptr"); return nullptr; } TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); @@ -120,12 +129,14 @@ std::shared_ptr ParallelTaskDispatcherBase::DelayDispatch( APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch execute failed"); return nullptr; } + APP_LOGI("ParallelTaskDispatcherBase::DelayDispatch end"); return innerTask; } std::shared_ptr ParallelTaskDispatcherBase::AsyncGroupDispatch( const std::shared_ptr &group, const std::shared_ptr &runnable) { + APP_LOGI("ParallelTaskDispatcherBase::AsyncGroupDispatch start"); if (group == nullptr) { APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch group is nullptr"); return nullptr; @@ -161,6 +172,7 @@ std::shared_ptr ParallelTaskDispatcherBase::AsyncGroupDispatch( APP_LOGE("ParallelTaskDispatcherBase::AsyncGroupDispatch execute failed"); return nullptr; } + APP_LOGI("ParallelTaskDispatcherBase::AsyncGroupDispatch end"); return innerTask; } diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp index 6e8c40eb174a7b2066441e8450b32500711a78a1..48e37f068ef063c144b9a35af6d466a9853dd858 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp @@ -44,7 +44,7 @@ std::string SerialTaskDispatcher::GetDispatcherName() ErrCode SerialTaskDispatcher::SyncDispatch(const std::shared_ptr &runnable) { - APP_LOGD("SerialTaskDispatcher::SyncDispatch begin"); + APP_LOGI("SerialTaskDispatcher::SyncDispatch start"); if (Check(runnable) != ERR_OK) { APP_LOGE("SerialTaskDispatcher::SyncDispatch check failed"); return ERR_APPEXECFWK_CHECK_FAILED; @@ -65,12 +65,13 @@ ErrCode SerialTaskDispatcher::SyncDispatch(const std::shared_ptr &runn innerSyncTask->WaitTask(); TracePointAfterPost(innerTask, false, DISPATCHER_TAG); - APP_LOGD("SerialTaskDispatcher::SyncDispatch end"); + APP_LOGI("SerialTaskDispatcher::SyncDispatch end"); return ERR_OK; } std::shared_ptr SerialTaskDispatcher::AsyncDispatch(const std::shared_ptr &runnable) { + APP_LOGI("SerialTaskDispatcher::AsyncDispatch start"); if (Check(runnable) != ERR_OK) { APP_LOGE("SerialTaskDispatcher::AsyncDispatch Check failed"); return nullptr; @@ -82,13 +83,15 @@ std::shared_ptr SerialTaskDispatcher::AsyncDispatch(const std::shared return nullptr; } TracePointBeforePost(innerTask, true, ASYNC_DISPATCHER_TAG); - APP_LOGD("SerialTaskDispatcher::AsyncDispatch into new async task"); + APP_LOGI("SerialTaskDispatcher::AsyncDispatch into new async task"); OnNewTaskIn(innerTask); + APP_LOGI("SerialTaskDispatcher::AsyncDispatch end"); return innerTask; } std::shared_ptr SerialTaskDispatcher::DelayDispatch(const std::shared_ptr &runnable, long delayMs) { + APP_LOGI("SerialTaskDispatcher::DelayDispatch start"); if (executor_ == nullptr) { APP_LOGE("SerialTaskDispatcher::DelayDispatch executor_ is nullptr"); return nullptr; @@ -111,14 +114,13 @@ std::shared_ptr SerialTaskDispatcher::DelayDispatch(const std::shared APP_LOGE("SerialTaskDispatcher::DelayDispatch execute failed"); return nullptr; } - + APP_LOGI("SerialTaskDispatcher::DelayDispatch end"); return innerTask; } ErrCode SerialTaskDispatcher::OnNewTaskIn(std::shared_ptr &task) { - APP_LOGD("SerialTaskDispatcher::OnNewTaskIn begin"); - + APP_LOGI("SerialTaskDispatcher::OnNewTaskIn start"); ErrCode code = Prepare(task); if (code != ERR_OK) { APP_LOGE("SerialTaskDispatcher::OnNewTaskIn Prepare failed"); @@ -132,12 +134,13 @@ ErrCode SerialTaskDispatcher::OnNewTaskIn(std::shared_ptr &task) } Schedule(); - APP_LOGD("SerialTaskDispatcher::OnNewTaskIn end"); + APP_LOGI("SerialTaskDispatcher::OnNewTaskIn end"); return ERR_OK; } ErrCode SerialTaskDispatcher::Prepare(std::shared_ptr &task) { + APP_LOGI("SerialTaskDispatcher::Prepare start"); if (task == nullptr) { APP_LOGE("SerialTaskDispatcher::Prepare task is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; @@ -170,48 +173,51 @@ ErrCode SerialTaskDispatcher::Prepare(std::shared_ptr &task) const std::function onTaskDone = [&]() { OnTaskDone(); }; ptrlistener->Callback(onTaskDone); task->AddTaskListener(ptrlistener); + APP_LOGI("SerialTaskDispatcher::Prepare end"); return ERR_OK; } void SerialTaskDispatcher::OnTaskDone() { - // isExhausted: is an inaccurate judge indicate that the workingTasks is empty.If true, do double - check. + APP_LOGI("SerialTaskDispatcher::OnTaskDone start"); bool isExhausted = workingTasks_.Empty(); DoNext(isExhausted); - // APP_LOGD("SerialTaskDispatcher::OnTaskDone end, running=%d", running.load()); + APP_LOGI("SerialTaskDispatcher::OnTaskDone end"); } bool SerialTaskDispatcher::Schedule() { bool init = false; if (!running_.compare_exchange_strong(init, true)) { - APP_LOGD("SerialTaskDispatcher::schedule already running"); + APP_LOGW("SerialTaskDispatcher::schedule already running"); return false; } - APP_LOGD("SerialTaskDispatcher::Schedule do next"); + APP_LOGI("SerialTaskDispatcher::Schedule do next"); return DoNext(false); } bool SerialTaskDispatcher::DoNext(bool isExhausted) { + APP_LOGI("SerialTaskDispatcher::DoNext start"); std::shared_ptr nextptr = nullptr; { std::unique_lock lock(mutex_); nextptr = workingTasks_.Poll(); if (nextptr == nullptr) { running_.store(false); - APP_LOGD("SerialTaskDispatcher::DoNext no more task"); + APP_LOGW("SerialTaskDispatcher::DoNext no more task"); return false; } } DoWork(nextptr); - APP_LOGD("SerialTaskDispatcher::DoNext end"); + APP_LOGI("SerialTaskDispatcher::DoNext end"); return true; } void SerialTaskDispatcher::DoWork(std::shared_ptr &task) { + APP_LOGI("SerialTaskDispatcher::DoWork called."); // |task| mustn't be null executor_->Execute(task); } diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp index d81c25902426034eb6f8f29c7d4ff520ca2a594a..e6e176164b19d04fbb185d7e894f764ac19ce3b4 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/spec_task_dispatcher.cpp @@ -31,53 +31,74 @@ SpecTaskDispatcher::SpecTaskDispatcher( ErrCode SpecTaskDispatcher::SyncDispatch(const std::shared_ptr &runnable) { - APP_LOGD("SpecTaskDispatcher::SyncDispatch begin"); - if (Check(runnable) != ERR_OK || handler_ == nullptr) { + APP_LOGI("SpecTaskDispatcher::SyncDispatch start"); + if (handler_ == nullptr) { + APP_LOGE("SpecTaskDispatcher::SyncDispatch handler is nullptr"); + return ERR_APPEXECFWK_CHECK_FAILED; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("SpecTaskDispatcher::SyncDispatch check failed"); return ERR_APPEXECFWK_CHECK_FAILED; } std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); if (innerTask == nullptr) { + APP_LOGE("SpecTaskDispatcher::SyncDispatch innerTask is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; } TracePointBeforePost(innerTask, false, SYNC_DISPATCHER_TAG); - APP_LOGD("SpecTaskDispatcher::SyncDispatch into new sync task"); + APP_LOGI("SpecTaskDispatcher::SyncDispatch into new sync task"); handler_->DispatchSync(runnable); - // innerSyncTask->WaitTask(); TracePointAfterPost(innerTask, false, DISPATCHER_TAG); - APP_LOGD("SpecTaskDispatcher::SyncDispatch end"); + APP_LOGI("SpecTaskDispatcher::SyncDispatch end"); return ERR_OK; } std::shared_ptr SpecTaskDispatcher::AsyncDispatch(const std::shared_ptr &runnable) { - if (Check(runnable) != ERR_OK || handler_ == nullptr) { + APP_LOGI("SpecTaskDispatcher::AsyncDispatch start"); + if (handler_ == nullptr) { + APP_LOGE("SpecTaskDispatcher::AsyncDispatch handler is nullptr"); + return nullptr; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("SpecTaskDispatcher::AsyncDispatch check failed"); return nullptr; } std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); if (innerTask == nullptr) { + APP_LOGE("SpecTaskDispatcher::AsyncDispatch innerTask is nullptr"); return nullptr; } TracePointBeforePost(innerTask, true, ASYNC_DISPATCHER_TAG); - APP_LOGD("SpecTaskDispatcher::AsyncDispatch into new async task"); + APP_LOGI("SpecTaskDispatcher::AsyncDispatch into new async task"); handler_->Dispatch(runnable); + APP_LOGI("SpecTaskDispatcher::AsyncDispatch end"); return innerTask; } std::shared_ptr SpecTaskDispatcher::DelayDispatch(const std::shared_ptr &runnable, long delayMs) { - if (Check(runnable) != ERR_OK || handler_ == nullptr) { + APP_LOGI("SpecTaskDispatcher::DelayDispatch start"); + if (handler_ == nullptr) { + APP_LOGE("SpecTaskDispatcher::DelayDispatch handler is nullptr"); + return nullptr; + } + if (Check(runnable) != ERR_OK) { + APP_LOGE("SpecTaskDispatcher::DelayDispatch check failed"); return nullptr; } std::shared_ptr innerTask = std::make_shared(runnable, GetPriority(), shared_from_this()); if (innerTask == nullptr) { + APP_LOGE("SpecTaskDispatcher::DelayDispatch innerTask is nullptr"); return nullptr; } TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); handler_->Dispatch(runnable, delayMs); + APP_LOGI("SpecTaskDispatcher::DelayDispatch end"); return innerTask; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp index 237bc31930ba384fbdf158fe6e835c35ba2c41ea..9e22e53a262b679e845cfa591503af978625e593 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp @@ -23,6 +23,7 @@ TaskDispatcherContext::TaskDispatcherContext() globalDispatchers_.resize(PRIORITY_COUNT); config_ = std::make_shared(); if (config_ == nullptr) { + APP_LOGE("TaskDispatcherContext::TaskDispatcherContext config is nullptr"); executor_ = nullptr; } else { executor_ = std::make_shared(config_); @@ -40,12 +41,11 @@ TaskDispatcherContext::TaskDispatcherContext(const std::shared_ptr TaskDispatcherContext::~TaskDispatcherContext() { - if (executor_) { - APP_LOGD("TaskDispatcherContext::~TaskDispatcherContext() terminate"); + APP_LOGI("TaskDispatcherContext::~TaskDispatcherContext() terminate"); executor_->Terminate(false); } - APP_LOGD("TaskDispatcherContext::~TaskDispatcherContext"); + APP_LOGI("TaskDispatcherContext::~TaskDispatcherContext end"); } std::shared_ptr TaskDispatcherContext::GetWorkerPoolConfig() const @@ -55,54 +55,67 @@ std::shared_ptr TaskDispatcherContext::GetWorkerPoolConfig() c std::map TaskDispatcherContext::GetWorkerThreadsInfo() const { + APP_LOGI("TaskDispatcherContext::GetWorkerThreadsInfo called"); if (executor_ != nullptr) { return executor_->GetWorkerThreadsInfo(); } std::map map; + APP_LOGE("TaskDispatcherContext::GetWorkerThreadsInfo executor is nullptr"); return map; } std::map, std::string> TaskDispatcherContext::GetSerialDispatchers() const { + APP_LOGI("TaskDispatcherContext::GetSerialDispatchers called"); return serialDispatchers_; } int TaskDispatcherContext::GetWaitingTasksCount() const { + APP_LOGI("TaskDispatcherContext::GetWaitingTasksCount called"); if (executor_ != nullptr) { return executor_->GetPendingTasksSize(); } + APP_LOGE("TaskDispatcherContext::GetWaitingTasksCount executor is nullptr"); return 0; } long TaskDispatcherContext::GetTaskCounter() const { + APP_LOGI("TaskDispatcherContext::GetTaskCounter called"); if (executor_ != nullptr) { return executor_->GetTaskCounter(); } + APP_LOGE("TaskDispatcherContext::GetTaskCounter executor is nullptr"); return 0; } std::shared_ptr TaskDispatcherContext::CreateSerialDispatcher( const std::string &name, TaskPriority priority) { + APP_LOGI("TaskDispatcherContext::CreateSerialDispatcher start"); if (executor_ == nullptr) { + APP_LOGE("TaskDispatcherContext::CreateSerialDispatcher executor is nullptr"); return nullptr; } std::shared_ptr serialDispatcher = std::make_shared(name, priority, executor_); serialDispatchers_.insert(std::pair, std::string>(serialDispatcher, name)); + APP_LOGI("TaskDispatcherContext::CreateSerialDispatcher end"); return serialDispatcher; } std::shared_ptr TaskDispatcherContext::CreateParallelDispatcher( const std::string &name, TaskPriority priority) { + APP_LOGI("TaskDispatcherContext::CreateParallelDispatcher start"); if (executor_ == nullptr) { + APP_LOGE("TaskDispatcherContext::CreateParallelDispatcher executor is nullptr"); return nullptr; } std::shared_ptr parallelTaskDispatcher = std::make_shared(name, priority, executor_); + APP_LOGI("TaskDispatcherContext::CreateParallelDispatcher end"); return parallelTaskDispatcher; } @@ -123,32 +136,35 @@ int TaskDispatcherContext::MapPriorityIndex(TaskPriority priority) const std::shared_ptr TaskDispatcherContext::GetGlobalTaskDispatcher(TaskPriority priority) { + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher start"); std::unique_lock lock(mtx_); int index = MapPriorityIndex(priority); std::shared_ptr dispatcher = globalDispatchers_[index]; if (dispatcher == nullptr) { - APP_LOGD("GetGlobalTaskDispatcher dispatcher is nullptr "); + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher dispatcher is nullptr "); if (executor_ == nullptr) { - APP_LOGE("GetGlobalTaskDispatcher executor_ is nullptr "); + APP_LOGE("TaskDispatcherContext::GetGlobalTaskDispatcher executor_ is nullptr "); return nullptr; } dispatcher = std::make_shared(priority, executor_); if (globalDispatchers_[index] == nullptr) { - APP_LOGD("GetGlobalTaskDispatcher dispatcher compareAndSet "); + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher dispatcher compareAndSet "); globalDispatchers_.insert((globalDispatchers_.begin() + index), dispatcher); } } - + APP_LOGI("TaskDispatcherContext::GetGlobalTaskDispatcher end"); return dispatcher; } ErrCode TaskDispatcherContext::Shutdown(bool force) { + APP_LOGI("TaskDispatcherContext::Shutdown start"); if (executor_ == nullptr) { APP_LOGE("TaskDispatcherContext::Shutdown executor_ is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; } executor_->Terminate(force); + APP_LOGI("TaskDispatcherContext::Shutdown end"); return ERR_OK; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp b/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp index caf0aa95175bf275fa73086cac2b865dbd3ce28f..a8d0c7a42f4dae87d84caf7959f6a70c019fa7b3 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp @@ -24,8 +24,9 @@ BarrierHandler::BarrierHandler(const std::shared_ptr &executor) ErrCode BarrierHandler::AddBarrier(std::shared_ptr &barrierTask) { + APP_LOGI("BarrierHandler::AddBarrier start"); if (ListenToTask(barrierTask) != ERR_OK) { - APP_LOGE("BarrierHandler::addBarrier listenToTask failed"); + APP_LOGE("BarrierHandler::AddBarrier listenToTask failed"); return ERR_APPEXECFWK_CHECK_FAILED; }; @@ -35,44 +36,51 @@ ErrCode BarrierHandler::AddBarrier(std::shared_ptr &barrierTask) std::shared_ptr pair = barrierQueue_.size() == 0 ? nullptr : barrierQueue_.back(); if ((pair == nullptr) || ((!HasTask(pair->tasks_)) && (pair->barrier_ == nullptr))) { execNow = true; + APP_LOGI("BarrierHandler::AddBarrier need execute now"); } if ((pair == nullptr) || (pair->barrier_ != nullptr)) { std::set> tmp; std::shared_ptr barrierPair = std::make_shared(tmp, barrierTask); if (barrierPair == nullptr) { + APP_LOGE("BarrierHandler::AddBarrier barrierPair is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; } barrierQueue_.push_back(barrierPair); - + APP_LOGI("BarrierHandler::AddBarrier barrierQueue push barrierPair"); } else { pair->barrier_ = barrierTask; } } - APP_LOGD("Barrier.addBarrier need execute now: %{public}d", execNow); if (execNow) { + APP_LOGI("BarrierHandler::AddBarrier execute task"); executor_->Execute(barrierTask); } + APP_LOGI("BarrierHandler::AddBarrier end"); return ERR_OK; } ErrCode BarrierHandler::Intercept(std::shared_ptr &task) { + APP_LOGI("BarrierHandler::Intercept start"); if (ListenToTask(task) != ERR_OK) { - APP_LOGE("BarrierHandler::intercept listenToTask failed"); + APP_LOGE("BarrierHandler::Intercept listenToTask failed"); return ERR_APPEXECFWK_CHECK_FAILED; }; // afterBarrier means is intercepted. bool intercepted = AddTaskAfterBarrier(task); if (intercepted) { - APP_LOGD("Barrier.intercept intercepted a task."); + APP_LOGI("BarrierHandler::Intercept intercepted a task."); } - return intercepted ? ERR_APPEXECFWK_INTERCEPT_TASK_EXECUTE_SUCCESS : ERR_APPEXECFWK_CHECK_FAILED; + ErrCode result = intercepted ? ERR_APPEXECFWK_INTERCEPT_TASK_EXECUTE_SUCCESS : ERR_APPEXECFWK_CHECK_FAILED; + APP_LOGI("BarrierHandler::Intercept end, result:%{public}d", result); + return result; } ErrCode BarrierHandler::ListenToTask(std::shared_ptr &task) { + APP_LOGI("BarrierHandler::ListenToTask start"); std::shared_ptr ptrlistener = std::make_shared(); if (ptrlistener == nullptr) { APP_LOGE("BarrierHandler::listenToTask make shared MyTaskListener is nullptr"); @@ -81,11 +89,13 @@ ErrCode BarrierHandler::ListenToTask(std::shared_ptr &task) const std::function onTaskDone = std::bind(&BarrierHandler::OnTaskDone, this, task); ptrlistener->Callback(onTaskDone); task->AddTaskListener(ptrlistener); + APP_LOGI("BarrierHandler::ListenToTask end"); return ERR_OK; } void BarrierHandler::OnTaskDone(std::shared_ptr &task) { + APP_LOGI("BarrierHandler::OnTaskDone start"); // remove from head of queue. // Under the premise that task cannot be reused. bool removed = false; @@ -96,11 +106,11 @@ void BarrierHandler::OnTaskDone(std::shared_ptr &task) if (HasTask(barrierPair->tasks_)) { removed = barrierPair->tasks_.erase(task) == 0 ? false : true; if (barrierPair->tasks_.empty() && (barrierPair->barrier_ != nullptr)) { - APP_LOGD("Barrier.onTaskDone execute barrier task after task done."); + APP_LOGI("Barrier.onTaskDone execute barrier task after task done."); executor_->Execute(barrierPair->barrier_); } } else if (task == (barrierPair->barrier_)) { - APP_LOGD("Barrier.onTaskDone remove a barrier."); + APP_LOGI("Barrier.onTaskDone remove a barrier."); barrierPair->barrier_ = nullptr; removed = true; // Driven to next barrier. @@ -116,11 +126,10 @@ void BarrierHandler::OnTaskDone(std::shared_ptr &task) } } else if (nextPair->barrier_ != nullptr) { - APP_LOGD("Barrier.onTaskDone execute barrier task after barrier done."); + APP_LOGI("Barrier.onTaskDone execute barrier task after barrier done."); executor_->Execute(nextPair->barrier_); } else { - // NOTREACHED. - APP_LOGD("Barrier.onTaskDone: Detected an empty node."); + APP_LOGW("Barrier.onTaskDone: Detected an empty node."); } } } @@ -128,12 +137,14 @@ void BarrierHandler::OnTaskDone(std::shared_ptr &task) } if (!removed) { - APP_LOGD("Barrier.onTaskDone: Task remove failed."); + APP_LOGI("Barrier.onTaskDone: Task remove failed."); } + APP_LOGI("BarrierHandler::OnTaskDone end"); } bool BarrierHandler::AddTaskAfterBarrier(std::shared_ptr &task) { + APP_LOGI("BarrierHandler::AddTaskAfterBarrier start"); std::unique_lock lock(barrierLock_); std::shared_ptr pair = barrierQueue_.size() == 0 ? nullptr : barrierQueue_.back(); if ((pair == nullptr) || (pair->barrier_ != nullptr)) { @@ -149,6 +160,7 @@ bool BarrierHandler::AddTaskAfterBarrier(std::shared_ptr &task) } else { pair->tasks_.insert(task); } + APP_LOGI("BarrierHandler::AddTaskAfterBarrier end"); return (barrierQueue_.size() > 1); } diff --git a/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp b/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp index ebe4759e836b5006be91f4c07fcb9bfd94ab67b7..bb005a0a77f3000b416525851f07f56d4ae378c0 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp @@ -38,26 +38,26 @@ void SyncTask::Run() { std::unique_lock lock(mutex_); auto threadId = std::this_thread::get_id(); - APP_LOGD("SyncTask::Run begin thread=%{public}zu", CalculateHashCode(threadId)); + APP_LOGI("SyncTask::Run begin thread=%{public}zu", CalculateHashCode(threadId)); Task::Run(); executed_.store(true); // |waitTask| may have been multi invoked. condition_variable_.notify_all(); - APP_LOGD("SyncTask::Run end thread=%{public}zu", CalculateHashCode(threadId)); + APP_LOGI("SyncTask::Run end thread=%{public}zu", CalculateHashCode(threadId)); } void SyncTask::WaitTask() { auto threadId = std::this_thread::get_id(); - APP_LOGD("SyncTask::WaitTask begin thread=%{public}zu", CalculateHashCode(threadId)); + APP_LOGI("SyncTask::WaitTask begin thread=%{public}zu", CalculateHashCode(threadId)); std::unique_lock lock(mutex_); while (executed_ == false) { condition_variable_.wait(lock); } - APP_LOGD("SyncTask::WaitTask end thread=%{public}zu", CalculateHashCode(threadId)); + APP_LOGI("SyncTask::WaitTask end thread=%{public}zu", CalculateHashCode(threadId)); } } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/src/task/task.cpp b/interfaces/innerkits/task_dispatcher/src/task/task.cpp index 9f3ce1544316e3e6c6ccd9344259decf7e1cb340..dd23ef89d615203af10abce79e6924d646deeb24 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/task.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/task.cpp @@ -30,8 +30,8 @@ Task::Task(const std::shared_ptr &runnable, const TaskPriority priorit runnable_ = runnable; priority_ = priority; baseTaskDispatcher_ = baseTaskDispatcher; - std::atomic_init(&state_, 0); - APP_LOGD("Task::Task init listener count=%{public}zu", taskListeners_.Size()); + std::atomic_init(&state_, 0U); + APP_LOGI("Task::Task init listener count=%{public}zu", taskListeners_.Size()); } Task::~Task() {} @@ -43,17 +43,17 @@ Task::~Task() */ void Task::Run() { - APP_LOGD("Task::Run task run called start"); + APP_LOGI("Task::Run task run called start"); if (runnable_ == nullptr) { APP_LOGI("Task::Run called runnable_ is null"); return; } // Task cannot be reused. if (EnterExecute()) { - APP_LOGD("Task::Run runnable_ Run called start"); + APP_LOGI("Task::Run runnable_ Run called start"); (*runnable_.get())(); } - APP_LOGD("Task::Run runnable_ Run called end"); + APP_LOGI("Task::Run runnable_ Run called end"); } /** @@ -95,11 +95,11 @@ long Task::GetSequence() const bool Task::Revoke() { if (runnable_ == nullptr) { - APP_LOGI("Task.Revoke called runnable_ is null"); + APP_LOGE("Task.Revoke called runnable_ is null"); return false; } RevokeResult result = SetRevoked(); - APP_LOGD("Task.Revoke result: %{public}u", result); + APP_LOGI("Task.Revoke result: %{public}u", result); if (result == SUCCESS) { OnTaskCanceled(); } @@ -113,7 +113,7 @@ bool Task::Revoke() */ void Task::AddTaskListener(const std::shared_ptr &listener) { - APP_LOGD("Task.AddTaskListener listener called start"); + APP_LOGI("Task.AddTaskListener listener called start"); taskListeners_.Offer(listener); } @@ -137,7 +137,7 @@ void Task::BeforeTaskExecute() void Task::AfterTaskExecute() { if ((state_ & EXECUTED) == EXECUTED) { - APP_LOGD("Task.AfterTaskExecute taskStage called AFTER_EXECUTE"); + APP_LOGI("Task.AfterTaskExecute taskStage called AFTER_EXECUTE"); ConcurrentQueueStatusUpdate(TaskStage::AFTER_EXECUTE); } } @@ -149,7 +149,7 @@ void Task::AfterTaskExecute() */ void Task::OnTaskCanceled() { - APP_LOGD("Task.OnTaskCanceled taskStage called REVOKED"); + APP_LOGI("Task.OnTaskCanceled taskStage called REVOKED"); ConcurrentQueueStatusUpdate(TaskStage::REVOKED); } @@ -160,17 +160,17 @@ void Task::OnTaskCanceled() */ bool Task::EnterExecute() { - int stateNotIn = EXECUTED | REVOKED; + unsigned int stateNotIn = EXECUTED | REVOKED; while (true) { - int value = state_.load(); + unsigned int value = state_.load(); if ((state_ & stateNotIn) == 0) { // Not executed or revoked if (state_.compare_exchange_strong(value, EXECUTED)) { - APP_LOGD("Task.EnterExecute return success"); + APP_LOGI("Task.EnterExecute return success"); return true; } } else { - APP_LOGD("Task.EnterExecute return fail, state=%{public}d, stateNotIn=%{public}d", value, stateNotIn); + APP_LOGE("Task.EnterExecute return fail, state=%{public}d, stateNotIn=%{public}d", value, stateNotIn); return false; } } @@ -179,18 +179,18 @@ bool Task::EnterExecute() Task::RevokeResult Task::SetRevoked() { while (true) { - int value = state_.load(); + unsigned int value = state_.load(); if ((value & REVOKED) == REVOKED) { - APP_LOGD("Task.SetRevoked return ALREADY_REVOKED"); + APP_LOGW("Task.SetRevoked return ALREADY_REVOKED"); return ALREADY_REVOKED; } if ((value & EXECUTED) == 0) { if (state_.compare_exchange_strong(value, REVOKED)) { - APP_LOGD("Task.SetRevoked return SUCCESS"); + APP_LOGI("Task.SetRevoked return SUCCESS"); return SUCCESS; } } else { - APP_LOGD("Task.SetRevoked return FAIL"); + APP_LOGE("Task.SetRevoked return FAIL"); return FAIL; } } @@ -198,7 +198,7 @@ Task::RevokeResult Task::SetRevoked() void Task::ConcurrentQueueStatusUpdate(const TaskStage::TASKSTAGE taskstage) { - APP_LOGD("Task.ConcurrentQueueStatusUpdate taskListeners_ called start"); + APP_LOGI("Task.ConcurrentQueueStatusUpdate taskListeners_ called start"); for (auto iter = taskListeners_.Begin(); iter != taskListeners_.End(); iter++) { (*iter)->OnChanged(taskstage); } diff --git a/interfaces/innerkits/task_dispatcher/src/threading/default_thread_factory.cpp b/interfaces/innerkits/task_dispatcher/src/threading/default_thread_factory.cpp index 8f1bad5e0701d1968bc5f6d60f595b6a738fab71..7b8d379181f5e46ea0a5d86c80c826d29fc30f12 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/default_thread_factory.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/default_thread_factory.cpp @@ -28,9 +28,9 @@ std::shared_ptr DefaultThreadFactory::Create() int value = std::atomic_fetch_add(&index_, 1); std::string name = std::string("PoolThread-") + std::to_string(value); pThread->thread_name_ = name; - APP_LOGD("DefaultThreadFactory::Create thread name is %{public}s", name.c_str()); + APP_LOGI("DefaultThreadFactory::Create thread name is %{public}s", name.c_str()); } else { - APP_LOGD("DefaultThreadFactory::Create error"); + APP_LOGE("DefaultThreadFactory::Create error, thread is nullptr"); } return pThread; diff --git a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp index 4aec05bb922344420684bd8a76326b6ded829049..406f79dd31a2506163532de044de66a5838cd0cc 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp @@ -30,15 +30,15 @@ TaskExecutor::TaskExecutor(const std::shared_ptr &config) : Wo TaskExecutor::~TaskExecutor() { if ((consumer_) && consumer_->joinable()) { - APP_LOGD("TaskExecutor::~TaskExecutor consumer is running"); + APP_LOGI("TaskExecutor::~TaskExecutor consumer is running"); consumer_->join(); } - APP_LOGD("TaskExecutor::~TaskExecutor"); + APP_LOGI("TaskExecutor::~TaskExecutor"); } void TaskExecutor::Execute(const std::shared_ptr &task) { - APP_LOGD("TaskExecutor::Execute begin"); + APP_LOGI("TaskExecutor::Execute begin"); task->SetSequence(GetAndIncrement(sequence)); std::shared_ptr executor = shared_from_this(); @@ -50,12 +50,12 @@ void TaskExecutor::Execute(const std::shared_ptr &task) APP_LOGW("TaskExecutor::Execute rejected a task"); } } - APP_LOGD("TaskExecutor::Execute end"); + APP_LOGI("TaskExecutor::Execute end"); } ErrCode TaskExecutor::DoWorks(const std::shared_ptr &worker) { - APP_LOGD("TaskExecutor::DoWorks begin"); + APP_LOGI("TaskExecutor::DoWorks begin"); if (worker == nullptr) { APP_LOGE("TaskExecutor::DoWorks worker is nullptr"); return ERR_APPEXECFWK_CHECK_FAILED; @@ -70,7 +70,7 @@ ErrCode TaskExecutor::DoWorks(const std::shared_ptr &worker) bool isInterrupted = false; bool done = false; while (((task != nullptr && done == false) || ((task = GetTask(worker)) != nullptr))) { - APP_LOGD("TaskExecutor::DoWorks loop tasks."); + APP_LOGI("TaskExecutor::DoWorks loop tasks."); BeforeRun(task); @@ -85,7 +85,7 @@ ErrCode TaskExecutor::DoWorks(const std::shared_ptr &worker) done = true; } OnWorkerExit(worker, isInterrupted); - APP_LOGD("TaskExecutor::DoWorks end"); + APP_LOGI("TaskExecutor::DoWorks end"); return ERR_OK; } std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr &workerThread) @@ -96,33 +96,33 @@ std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr for (;;) { if (terminated_.load() && pendingTasks_->Empty()) { - APP_LOGD("TaskExecutor::GetTask end: loop thread %{public}s is terminated", + APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is terminated", workerThread->GetThreadName().c_str()); DecrementThread(); return nullRunnable; } int workerCount = GetWorkCount(); - APP_LOGD("TaskExecutor::GetTask workerCount:%{public}d, GetCoreThreadCount: %{public}d", + APP_LOGI("TaskExecutor::GetTask workerCount:%{public}d, GetCoreThreadCount: %{public}d", workerCount, GetCoreThreadCount()); bool needCheckTimeout = (workerCount > GetCoreThreadCount()); if (isTimeout && needCheckTimeout && pendingTasks_->Empty()) { - APP_LOGD("TaskExecutor::GetTask isTimeout is true"); + APP_LOGI("TaskExecutor::GetTask isTimeout is true"); if (CompareAndDecNum(workerCount)) { - APP_LOGD("TaskExecutor::GetTask end: loop thread %{public}s is timeout", + APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is timeout", workerThread->GetThreadName().c_str()); return nullRunnable; } continue; } - APP_LOGD("TaskExecutor::GetTask need timeout=%{public}d", needCheckTimeout); + APP_LOGI("TaskExecutor::GetTask need timeout=%{public}d", needCheckTimeout); std::shared_ptr next = needCheckTimeout ? pendingTasks_->Poll(GetKeepAliveTime()) : pendingTasks_->Take(); if (next != nullptr && next->task_ != nullptr) { - APP_LOGD("TaskExecutor::GetTask end: loop thread %{public}s get next task", + APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s get next task", workerThread->GetThreadName().c_str()); return next->task_; } @@ -132,10 +132,10 @@ std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr void TaskExecutor::Terminate(bool force) { - APP_LOGD("TaskExecutor::Terminate begin"); + APP_LOGI("TaskExecutor::Terminate begin"); TerminateConsumer(); ClosePool(force); - APP_LOGD("TaskExecutor::Terminate end"); + APP_LOGI("TaskExecutor::Terminate end"); } void TaskExecutor::AfterRun(const std::shared_ptr &task) @@ -152,7 +152,7 @@ bool TaskExecutor::DelayExecute(const Runnable &task, long delayMs) { if (delayMs <= 0) { task(); - APP_LOGD("TaskExecutor::DelayExecute end and delayMs less than 0"); + APP_LOGI("TaskExecutor::DelayExecute end and delayMs less than 0"); return true; } if (terminated_.load()) { @@ -192,10 +192,10 @@ bool TaskExecutor::EnsureConsumeStarted() if (consumer_ == nullptr) { consumer_ = std::make_shared(&TaskExecutor::Consume, this); if (consumer_ == nullptr) { - APP_LOGD("TaskExecutor::EnsureConsumeStarted consumer_ is nullptr"); + APP_LOGE("TaskExecutor::EnsureConsumeStarted consumer_ is nullptr"); return false; } - APP_LOGD("TaskExecutor::EnsureConsumeStarted start a delay task consumer"); + APP_LOGI("TaskExecutor::EnsureConsumeStarted start a delay task consumer"); } } } @@ -206,16 +206,16 @@ void TaskExecutor::Consume() { for (;;) { if (terminated_.load() && delayTasks_->Empty()) { - APP_LOGD("TaskExecutor::Consume delay task is empty"); + APP_LOGI("TaskExecutor::Consume delay task is empty"); break; } std::shared_ptr delayTaskWrapper = delayTasks_->Take(); if (delayTaskWrapper == nullptr || delayTaskWrapper->runnable_ == nullptr) { - APP_LOGD("TaskExecutor::Consume delayTaskWrapper is nullptr"); + APP_LOGE("TaskExecutor::Consume delayTaskWrapper is nullptr"); return; }; (delayTaskWrapper->runnable_)(); - APP_LOGD("TaskExecutor::Consume after run"); + APP_LOGI("TaskExecutor::Consume after run"); } } diff --git a/interfaces/innerkits/task_dispatcher/src/threading/work_thread.cpp b/interfaces/innerkits/task_dispatcher/src/threading/work_thread.cpp index 04f135a5cf244f664ec38a11691de1928bde03c0..ece157d5ba083b1dd6cab7f608f2fec7143ca0d2 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/work_thread.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/work_thread.cpp @@ -30,10 +30,10 @@ WorkerThread::WorkerThread(const std::shared_ptr &delegate, const std: void WorkerThread::Join() { if ((thread_) && (thread_->thread_) && thread_->thread_->joinable()) { - APP_LOGD("WorkerThread::Join joinable thread"); + APP_LOGI("WorkerThread::Join joinable thread"); thread_->thread_->join(); } - APP_LOGD("WorkerThread::Join end"); + APP_LOGI("WorkerThread::Join end"); } void WorkerThread::CreateThread() @@ -48,7 +48,7 @@ void WorkerThread::CreateThread() // start a thread to run task function. thread_->thread_ = std::make_shared(task); - APP_LOGD("WorkerThread::CreateThread start thread. "); + APP_LOGI("WorkerThread::CreateThread start thread. "); } void WorkerThread::IncTaskCount() diff --git a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp index 4bdfa2289e977ad876d201170fd2ba9613da1029..137644970613b9da76e4abe79c47645dec7da7eb 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp @@ -23,7 +23,7 @@ const int WorkerPool::THREAD_UPPER_LIMIT = 256; const int WorkerPool::MAX_THREAD_LOWER_LIMIT = 1; const int WorkerPool::CORE_THREAD_LOWER_LIMIT = 0; const int WorkerPool::COUNT_BITS = sizeof(int) * __CHAR_BIT__ - 3; -const int WorkerPool::CAPACITY = (1 << COUNT_BITS) - 1; +const unsigned int WorkerPool::CAPACITY = (1 << COUNT_BITS) - 1; const int WorkerPool::RUNNING = (-(1 << COUNT_BITS)); const int WorkerPool::CLOSING = (0 << COUNT_BITS); const int WorkerPool::INTERRUPT = (1 << COUNT_BITS); @@ -44,7 +44,7 @@ WorkerPool::~WorkerPool() { control_ = 0; - APP_LOGD("WorkerPool::~WorkerPool"); + APP_LOGI("WorkerPool::~WorkerPool"); } bool WorkerPool::Init(const std::shared_ptr &config) @@ -128,7 +128,7 @@ int WorkerPool::GetMaxThreadCount(void) const int WorkerPool::GetWorkCount(void) const { - int value = control_.load(); + unsigned int value = control_.load(); return GetWorkingThreadNum(value); } @@ -147,19 +147,20 @@ std::map WorkerPool::GetWorkerThreadsInfo(void) void WorkerPool::ClosePool(bool interrupt) { - APP_LOGD("WorkerPool::ClosePool begin interrupt=%{public}d", interrupt); + APP_LOGI("WorkerPool::ClosePool begin interrupt=%{public}d", interrupt); std::unique_lock mLock(poolLock_); AdvanceStateTo(CLOSING); InterruptWorkers(); - APP_LOGD("WorkerPool::ClosePool end"); + APP_LOGI("WorkerPool::ClosePool end"); } void WorkerPool::InterruptWorkers(void) { - APP_LOGD("WorkerPool::InterruptWorkers begin"); + APP_LOGI("WorkerPool::InterruptWorkers begin"); if (guardThread_ == nullptr) { + APP_LOGE("WorkerPool::InterruptWorkers guardThread is nullptr"); return; } poolLock_.unlock(); @@ -174,18 +175,19 @@ void WorkerPool::InterruptWorkers(void) std::unique_lock lock(exitPoolLock_); exitGuard_.wait(lock); if (guardThread_->joinable()) { - APP_LOGD("WorkerPool::InterruptWorkers guardThread_ joinable"); + APP_LOGI("WorkerPool::InterruptWorkers guardThread_ joinable"); guardThread_->join(); - guardThread_ = nullptr; // 防止再次手动调用 + // Prevent manual call again + guardThread_ = nullptr; } } - APP_LOGD("WorkerPool::InterruptWorkers end"); + APP_LOGI("WorkerPool::InterruptWorkers end"); } void WorkerPool::CreateGuardThread() { - APP_LOGD("WorkerPool::CreateGuardThread START"); + APP_LOGI("WorkerPool::CreateGuardThread START"); if (guardThread_ != nullptr) { APP_LOGW("WorkerPool::CreateGuardThread guardThread_ is not nullptr"); return; @@ -205,11 +207,11 @@ void WorkerPool::CreateGuardThread() } if (stop_.load() && exitPool_.empty() && pool_.empty()) { exitGuard_.notify_all(); - APP_LOGD("WorkerPool::CreateGuardThread break while"); + APP_LOGI("WorkerPool::CreateGuardThread break while"); break; } } - APP_LOGD("WorkerPool::CreateGuardThread STOP"); + APP_LOGI("WorkerPool::CreateGuardThread STOP"); }; guardThread_ = std::make_shared(guardTask); @@ -238,16 +240,16 @@ bool WorkerPool::AddWorker(const std::shared_ptr &delegate, const std: std::shared_ptr newThread = nullptr; for (;;) { - int value = control_.load(); + unsigned int value = control_.load(); int num = GetWorkingThreadNum(value); if (num >= thread_limit_) { - APP_LOGD("WorkerPool::AddWorker thread count exceed limits, num=%{public}d, limits=%{public}d", + APP_LOGI("WorkerPool::AddWorker thread count exceed limits, num=%{public}d, limits=%{public}d", num, thread_limit_); break; } if (!IsRunning(value)) { - APP_LOGD("WorkerPool::AddWorker thread pool is not running. value=%{public}d, closing=%{public}d, " + APP_LOGI("WorkerPool::AddWorker thread pool is not running. value=%{public}d, closing=%{public}d, " "count_bits=%{public}d", value, CLOSING, @@ -264,35 +266,33 @@ bool WorkerPool::AddWorker(const std::shared_ptr &delegate, const std: newThread->CreateThread(); - APP_LOGD("WorkerPool::AddWorker create new thread"); + APP_LOGI("WorkerPool::AddWorker create new thread"); pool_.emplace_back(newThread); - APP_LOGD("POOL SIZE: %{public}zu", pool_.size()); - APP_LOGD("pool_ add end"); + APP_LOGI("WorkerPool::AddWorker pool_ add thread ,POOL SIZE: %{public}zu", pool_.size()); added = true; break; } - APP_LOGD("WorkerPool::AddWorker set thread state error. retry. "); + APP_LOGW("WorkerPool::AddWorker set thread state error. retry. "); } return added; } void WorkerPool::OnWorkerExit(const std::shared_ptr &worker, bool isInterrupted) { - std::unique_lock mLock(poolLock_); - APP_LOGD("WorkerPool::OnWorkerExit start"); - APP_LOGD("size:%{public}zu", pool_.size()); + APP_LOGI("WorkerPool::OnWorkerExit start, pool size: %{public}zu", pool_.size()); for (auto it = pool_.begin(); it != pool_.end(); it++) { if ((*it).get() == worker.get()) { - APP_LOGD("WorkerPool::OnWorkerExit erase current, size=%{public}zu, threads=%{public}d", + APP_LOGI("WorkerPool::OnWorkerExit erase current, size=%{public}zu, threads=%{public}d", pool_.size(), GetWorkingThreadNum(control_.load())); { std::unique_lock lock(exitPoolLock_); exitPool_.emplace_back(worker); + APP_LOGI("WorkerPool::OnWorkerExit exit notify all"); exit_.notify_all(); } pool_.erase(it); @@ -300,7 +300,7 @@ void WorkerPool::OnWorkerExit(const std::shared_ptr &worker, bool break; } } - APP_LOGD("WorkerPool::OnWorkerExit end"); + APP_LOGI("WorkerPool::OnWorkerExit end"); } void WorkerPool::AfterRun(const std::shared_ptr &task) @@ -309,7 +309,7 @@ void WorkerPool::AfterRun(const std::shared_ptr &task) void WorkerPool::BeforeRun(const std::shared_ptr &task) {} -int WorkerPool::GetWorkingThreadNum(int ctl) +unsigned int WorkerPool::GetWorkingThreadNum(unsigned int ctl) { return ctl & CAPACITY; } @@ -324,21 +324,21 @@ int WorkerPool::GetStateFromControl(int ctl) return ctl & ~CAPACITY; } -void WorkerPool::AdvanceStateTo(int target) +void WorkerPool::AdvanceStateTo(unsigned int target) { - APP_LOGD("WorkerPool::AdvanceStateTo begin"); + APP_LOGI("WorkerPool::AdvanceStateTo begin"); for (;;) { - int current = control_.load(); + unsigned int current = control_.load(); if ((current >= target) || CompareAndSet(control_, current, CombineToControl(target, GetWorkingThreadNum(current)))) { - APP_LOGD("WorkerPool::AdvanceStateTo break"); + APP_LOGI("WorkerPool::AdvanceStateTo break"); break; } } - APP_LOGD("WorkerPool::AdvanceStateTo end"); + APP_LOGI("WorkerPool::AdvanceStateTo end"); } -int WorkerPool::CombineToControl(int state, int count) +int WorkerPool::CombineToControl(unsigned int state, unsigned int count) { return state | count; } @@ -352,12 +352,12 @@ bool WorkerPool::CompareAndIncThreadNum(int expect) void WorkerPool::DecrementThread(void) { - APP_LOGD("WorkerPool::DecrementThread begin"); + APP_LOGI("WorkerPool::DecrementThread begin"); int curr = control_.load(); while (!CompareAndDecThreadNum(curr)) { curr = control_.load(); } - APP_LOGD("WorkerPool::DecrementThread end"); + APP_LOGI("WorkerPool::DecrementThread end"); } bool WorkerPool::CompareAndDecThreadNum(int expect) diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp index a764060c230d0608409dcae20c4dda0c6fad4964..dd2ada38bd637691bea5414e74e744e702fbbd11 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/base_task_dispatcher_test/base_task_dispatcher_test.cpp @@ -73,17 +73,10 @@ void BaseTaskDispatcherTest::TearDown() context = nullptr; ptrSerialTaskDispatcher = nullptr; } -std::string Now() -{ - time_t now = std::time(0); - char mbstr[10]; - std::strftime(mbstr, sizeof(mbstr), "%T", std::localtime(&now)); - return mbstr; -} const std::string Prefix(const std::string &name) { - return std::string(">>> ") + Now() + std::string(" ") + name + std::string(": "); + return std::string(">>> prefix :") + std::string(" ") + name + std::string(": "); } /** @@ -171,7 +164,7 @@ HWTEST_F(BaseTaskDispatcherTest, AsyncDispatchBarrier_0100, Function | MediumTes })); // async execute - ASSERT_LT(count.load(), 1); + EXPECT_LT(count.load(), 1); long sleep2 = 100; ptrSerialTaskDispatcher->AsyncDispatchBarrier(std::make_shared([&]() { @@ -182,7 +175,7 @@ HWTEST_F(BaseTaskDispatcherTest, AsyncDispatchBarrier_0100, Function | MediumTes GTEST_LOG_(INFO) << Prefix(name) << "AsyncDispatchBarrier-" << index << " thread " << std::this_thread::get_id() << ", sleep for " << sleep2 << " ms"; })); - ASSERT_LT(count.load(), 2); + EXPECT_LT(count.load(), 2); long wait = sleep1 + sleep2 + 100; GTEST_LOG_(INFO) << Prefix(name) << "wait for " << (wait); auto time = std::chrono::milliseconds(wait); @@ -202,7 +195,7 @@ HWTEST_F(BaseTaskDispatcherTest, CreateDispatchGroup_0100, Function | MediumTest { GTEST_LOG_(INFO) << "CreateDispatchGroup_0100 start"; std::shared_ptr gptr = ptrSerialTaskDispatcher->CreateDispatchGroup(); - ASSERT_TRUE(ptrSerialTaskDispatcher->GroupDispatchWait(gptr, 10)); + EXPECT_TRUE(ptrSerialTaskDispatcher->GroupDispatchWait(gptr, 10)); GTEST_LOG_(INFO) << "CreateDispatchGroup_0100 end"; } @@ -230,7 +223,7 @@ HWTEST_F(BaseTaskDispatcherTest, AsyncGroupDispatch_0100, Function | MediumTest })); // async execute - ASSERT_LT(count.load(), 1); + EXPECT_LT(count.load(), 1); long sleep2 = 100; ptrSerialTaskDispatcher->AsyncGroupDispatch(gptr, std::make_shared([&count, &sleep2, &name]() { @@ -241,7 +234,7 @@ HWTEST_F(BaseTaskDispatcherTest, AsyncGroupDispatch_0100, Function | MediumTest GTEST_LOG_(INFO) << Prefix(name) << "AsyncGroupDispatch-" << index << " thread " << std::this_thread::get_id() << ", sleep for " << sleep2 << " ms"; })); - ASSERT_LT(count.load(), 2); + EXPECT_LT(count.load(), 2); long wait = sleep1 + sleep2 + 100; GTEST_LOG_(INFO) << Prefix(name) << "wait for " << (wait); auto time = std::chrono::milliseconds(wait); @@ -285,7 +278,7 @@ HWTEST_F(BaseTaskDispatcherTest, ApplyDispatch_0100, Function | MediumTest | Lev }); ptrSerialTaskDispatcher->ApplyDispatch(repeats2, 10); // async execute - ASSERT_LT(count.load(), 20); + EXPECT_LT(count.load(), 20); long wait = sleep1 * 10 + sleep2 * 10 + 100 + 100; GTEST_LOG_(INFO) << Prefix(name) << "wait for " << (wait); auto time = std::chrono::milliseconds(wait); @@ -339,7 +332,7 @@ HWTEST_F(BaseTaskDispatcherTest, GroupDispatchWait_0100, Function | MediumTest | { GTEST_LOG_(INFO) << "GroupDispatchWait_0100 start"; std::shared_ptr gptr = ptrSerialTaskDispatcher->CreateDispatchGroup(); - ASSERT_TRUE(ptrSerialTaskDispatcher->GroupDispatchWait(gptr, 0)); + EXPECT_TRUE(ptrSerialTaskDispatcher->GroupDispatchWait(gptr, 0)); GTEST_LOG_(INFO) << "GroupDispatchWait_0100 end"; } diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp index 7822421c357c97acd0d166d364e50d5426b6304f..5347daaca1ff5357f1c146140a5356e7f9d4636c 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp @@ -87,7 +87,7 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_SyncDispatchTe std::shared_ptr parallelTaskDispatcherBase = CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); ErrCode errCode = parallelTaskDispatcherBase->SyncDispatch(nullptr); - ASSERT_TRUE(errCode == ERR_APPEXECFWK_CHECK_FAILED); + EXPECT_TRUE(errCode == ERR_APPEXECFWK_CHECK_FAILED); std::atomic count(0); EXPECT_EQ(count.load(), 0); std::shared_ptr rptr = std::make_shared([&]() { @@ -120,7 +120,7 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncDispatchT std::shared_ptr parallelTaskDispatcherBase = CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); std::shared_ptr revocable = parallelTaskDispatcherBase->AsyncDispatch(nullptr); - ASSERT_TRUE(revocable == nullptr); + EXPECT_TRUE(revocable == nullptr); std::atomic count(0); EXPECT_EQ(count.load(), 0); std::shared_ptr rptr = std::make_shared([&]() { @@ -177,7 +177,7 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_DelayDispatchT GTEST_LOG_(INFO) << name << " Runnable"; }); std::shared_ptr revocable = parallelTaskDispatcherBase->DelayDispatch(nullptr, 1000); - ASSERT_TRUE(revocable == nullptr); + EXPECT_TRUE(revocable == nullptr); GTEST_LOG_(INFO) << name << " end"; } @@ -235,6 +235,6 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDisp CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); std::shared_ptr revocable = parallelTaskDispatcherBase->AsyncGroupDispatch(nullptr, nullptr); - ASSERT_TRUE(revocable == nullptr); + EXPECT_TRUE(revocable == nullptr); GTEST_LOG_(INFO) << name << " end"; } \ No newline at end of file diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_test/parallel_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_test/parallel_task_dispatcher_test.cpp index f7a5cec774350ab5858e0a71daee11c236aa62ce..0fa744cf871a81d49a2ca88f1c12933c3d90cb52 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_test/parallel_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_test/parallel_task_dispatcher_test.cpp @@ -110,7 +110,7 @@ HWTEST(ParallelTaskDispatcherTest, ParallelTaskDispatcher_SyncDispatchBarrierTes std::shared_ptr parallelTaskDispatcher = CreateParallelTaskDispatcher(name, TaskPriority::DEFAULT); ErrCode result = parallelTaskDispatcher->SyncDispatchBarrier(nullptr); - ASSERT_TRUE(result == ERR_APPEXECFWK_CHECK_FAILED); + EXPECT_TRUE(result == ERR_APPEXECFWK_CHECK_FAILED); GTEST_LOG_(INFO) << name << " end"; } @@ -149,6 +149,6 @@ HWTEST(ParallelTaskDispatcherTest, ParallelTaskDispatcher_AsyncDispatchBarrierTe std::shared_ptr parallelTaskDispatcher = CreateParallelTaskDispatcher(name, TaskPriority::DEFAULT); ErrCode result = parallelTaskDispatcher->AsyncDispatchBarrier(nullptr); - ASSERT_TRUE(result == ERR_APPEXECFWK_CHECK_FAILED); + EXPECT_TRUE(result == ERR_APPEXECFWK_CHECK_FAILED); GTEST_LOG_(INFO) << name << " end"; } diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp index dcbcc7eb86b289c476c1d18f8af2b86e5e5364f0..e9033f2e9f97eb01595a6c7a5230394ea50192ab 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/serial_task_dispatcher_test/serial_task_dispatcher_test.cpp @@ -51,14 +51,14 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_SyncDispatchTest_1000, Tes std::shared_ptr dispatcher = std::make_shared(name, priority, executor); std::atomic count(0); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); dispatcher->SyncDispatch(std::make_shared([&count, &name]() { int index = count.fetch_add(1); - ASSERT_TRUE(index == 0); + EXPECT_TRUE(index == 0); GTEST_LOG_(INFO) << name + " task " + std::to_string(index) + " end"; })); - ASSERT_TRUE(count.load() == 1); + EXPECT_TRUE(count.load() == 1); GTEST_LOG_(INFO) << name + " end"; } @@ -221,21 +221,21 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_GetWorkingTasksSizeTest_00 auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); - ASSERT_EQ(dispatcher->GetWorkingTasksSize(), 2 - 1); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 2 - 1); } { long wait = 2000; auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); - ASSERT_EQ(dispatcher->GetWorkingTasksSize(), 1 - 1); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 1 - 1); } { long wait = 2000; auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); - ASSERT_EQ(dispatcher->GetWorkingTasksSize(), 0); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); } long wait = 5000; auto time = std::chrono::milliseconds(wait); @@ -271,14 +271,14 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_GetWorkingTasksSizeTest_00 auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); - ASSERT_EQ(dispatcher->GetWorkingTasksSize(), times - 1); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), times - 1); } { - long wait = 300 * times; + long wait = 300 * (long)times; auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); GTEST_LOG_(INFO) << name + " size: " + std::to_string(dispatcher->GetWorkingTasksSize()); - ASSERT_EQ(dispatcher->GetWorkingTasksSize(), 0); + EXPECT_EQ(dispatcher->GetWorkingTasksSize(), 0); } GTEST_LOG_(INFO) << name + " end"; @@ -302,39 +302,39 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_SyncDispatchTest_001, Test std::shared_ptr dispatcher = std::make_shared("", priority, executor); std::atomic count(0); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep1 = 2000; dispatcher->SyncDispatch(std::make_shared([&count, sleep = sleep1]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 0); + EXPECT_TRUE(index == 0); GTEST_LOG_(INFO) << "SerialTaskDispatcher_SyncDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); })); - ASSERT_TRUE(count.load() == 1); + EXPECT_TRUE(count.load() == 1); int sleep2 = 100; dispatcher->SyncDispatch(std::make_shared([&count, sleep = sleep2]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 1); + EXPECT_TRUE(index == 1); GTEST_LOG_(INFO) << "SerialTaskDispatcher_SyncDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); })); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); int sleep3 = 1000; dispatcher->SyncDispatch(std::make_shared([&count, sleep = sleep3]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 2); + EXPECT_TRUE(index == 2); GTEST_LOG_(INFO) << "SerialTaskDispatcher_SyncDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); })); - ASSERT_TRUE(count.load() == 3); + EXPECT_TRUE(count.load() == 3); long wait = 1000; GTEST_LOG_(INFO) << ("wait for " + std::to_string(wait)); @@ -353,7 +353,7 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_SyncDispatchTest_002, Test std::shared_ptr dispatcher = std::make_shared("", priority, executor); ErrCode errCode = dispatcher->SyncDispatch(nullptr); - ASSERT_TRUE(errCode == ERR_APPEXECFWK_CHECK_FAILED); + EXPECT_TRUE(errCode == ERR_APPEXECFWK_CHECK_FAILED); GTEST_LOG_(INFO) << name + " end"; } @@ -376,39 +376,39 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_AsyncDispatchTest_001, Tes std::shared_ptr dispatcher = std::make_shared("", priority, executor); std::atomic count(0); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep1 = 2000; dispatcher->AsyncDispatch(std::make_shared([&count, sleep = sleep1]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 0); + EXPECT_TRUE(index == 0); GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); })); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep2 = 1000; dispatcher->AsyncDispatch(std::make_shared([&count, sleep = sleep2]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 1); + EXPECT_TRUE(index == 1); GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); })); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep3 = 1000; dispatcher->AsyncDispatch(std::make_shared([&count, sleep = sleep3]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 2); + EXPECT_TRUE(index == 2); GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); })); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); { long wait = 100; @@ -420,28 +420,28 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_AsyncDispatchTest_001, Tes GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 1); + EXPECT_TRUE(count.load() == 1); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 3); + EXPECT_TRUE(count.load() == 3); } GTEST_LOG_(INFO) << name + " end"; @@ -456,7 +456,7 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_AsyncDispatchTest_002, Tes std::shared_ptr dispatcher = std::make_shared("", priority, executor); std::shared_ptr revocable = dispatcher->AsyncDispatch(nullptr); - ASSERT_TRUE(revocable == nullptr); + EXPECT_TRUE(revocable == nullptr); GTEST_LOG_(INFO) << name + " end"; } @@ -482,32 +482,32 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_001, Tes int sleep1 = 2000; dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { int index = count.fetch_add(1); - ASSERT_TRUE(index == 2); + EXPECT_TRUE(index == 2); GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); }), sleep1); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep2 = 1000; dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { int index = count.fetch_add(1); - ASSERT_TRUE(index == 0 || index == 1); + EXPECT_TRUE(index == 0 || index == 1); GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); }), sleep2); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep3 = 1000; dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep3]() { int index = count.fetch_add(1); - ASSERT_TRUE(index == 0 || index == 1); + EXPECT_TRUE(index == 0 || index == 1); GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_001 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); }), sleep3); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); { long wait = 100; @@ -519,7 +519,7 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_001, Tes GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); } { long wait = 500; @@ -527,14 +527,14 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_001, Tes auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); GTEST_LOG_(INFO) << ("wait for task, load= " + std::to_string(count.load())); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 3); + EXPECT_TRUE(count.load() == 3); } GTEST_LOG_(INFO) << name + " end"; @@ -568,7 +568,7 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_003, Tes int sleep1 = -2000; dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { int index = count.fetch_add(1); - ASSERT_TRUE(index == 1 || index == 0); + EXPECT_TRUE(index == 1 || index == 0); GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_003 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); }), @@ -577,7 +577,7 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_003, Tes int sleep2 = -1000; dispatcher->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { int index = count.fetch_add(1); - ASSERT_TRUE(index == 0 || index == 1); + EXPECT_TRUE(index == 0 || index == 1); GTEST_LOG_(INFO) << "SerialTaskDispatcher_DelayDispatchTest_003 task" + std::to_string(index) + " end, elapsed " + std::to_string(sleep); }), @@ -588,7 +588,7 @@ HWTEST(SerialTaskDispatcherTest, SerialTaskDispatcher_DelayDispatchTest_003, Tes GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); } GTEST_LOG_(INFO) << name + " end"; diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/BUILD.gn b/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/BUILD.gn index 83f95e817041e9171229785881254d493ed43f77..530fd6112789bfe1196a6c2266b74aaceb31f5d2 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/BUILD.gn +++ b/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/BUILD.gn @@ -36,7 +36,7 @@ ohos_unittest("SpecDispatcherConfigTest") { "${dispatcher_path}/src/threading/worker_pool.cpp", ] - sources += [ "spec_dispatcher_config_test .cpp" ] + sources += [ "spec_dispatcher_config_test.cpp" ] configs = [ "${dispatcher_path}/test:dispatcher_test_config" ] diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test .cpp b/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test.cpp similarity index 93% rename from interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test .cpp rename to interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test.cpp index 8d5e139694f0f7312d3ac8d24a692bf09f7af038..0292695e797e092dd96a3aafdcf64ebaff7589b9 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test .cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/spec_dispatcher_config_test/spec_dispatcher_config_test.cpp @@ -65,8 +65,8 @@ HWTEST(SpecDispatcherConfigTest, SpecDispatcherConfig_0100, Function | MediumTes std::string dispatcherName = "SpecDispatcherConfig_0100"; TaskPriority taskPriority = TaskPriority::DEFAULT; std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); - ASSERT_EQ(config->GetName(), dispatcherName); - ASSERT_EQ(config->GetPriority(), TaskPriority::DEFAULT); + EXPECT_EQ(config->GetName(), dispatcherName); + EXPECT_EQ(config->GetPriority(), TaskPriority::DEFAULT); GTEST_LOG_(INFO) << "SpecDispatcherConfig_0100 end"; } /** @@ -81,7 +81,7 @@ HWTEST(SpecDispatcherConfigTest, GetPriority_0100, Function | MediumTest | Level std::string dispatcherName = "GetPriority_0100"; TaskPriority taskPriority = TaskPriority::DEFAULT; std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); - ASSERT_EQ(config->GetPriority(), TaskPriority::DEFAULT); + EXPECT_EQ(config->GetPriority(), TaskPriority::DEFAULT); GTEST_LOG_(INFO) << "GetPriority_0100 end"; } /** @@ -96,6 +96,6 @@ HWTEST(SpecDispatcherConfigTest, GetName_0100, Function | MediumTest | Level1) std::string dispatcherName = "GetName_0100"; TaskPriority taskPriority = TaskPriority::DEFAULT; std::shared_ptr config = std::make_shared(dispatcherName, taskPriority); - ASSERT_EQ(config->GetName(), dispatcherName); + EXPECT_EQ(config->GetName(), dispatcherName); GTEST_LOG_(INFO) << "GetName_0100 end"; } diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp index d01bda6fb0385adc9783a1749e01615c34168a83..8c4ad4db71213c977e0af2d1bfb6469eec01996b 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp @@ -94,7 +94,7 @@ HWTEST(SpecTaskDispatcherTest, SpecTaskDispatcher_0100, Function | MediumTest | GTEST_LOG_(INFO) << "SpecTaskDispatcher_0100 start"; std::shared_ptr ptr = CreateSpecTaskDispatcher(); // same to func CreateSpecTaskDispatcher TaskPriority - ASSERT_EQ(ptr->GetPriority(), TaskPriority::HIGH); + EXPECT_EQ(ptr->GetPriority(), TaskPriority::HIGH); GTEST_LOG_(INFO) << "SpecTaskDispatcher_0100 end"; } @@ -114,36 +114,36 @@ HWTEST(SpecTaskDispatcherTest, SyncDispatch_0100, Function | MediumTest | Level1 // task runs synchronized // use elapsed time to identify a task. std::atomic count(0); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep1 = 2000; ptr->SyncDispatch(std::make_shared([&count, sleep = sleep1]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 0); + EXPECT_TRUE(index == 0); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); })); - ASSERT_TRUE(count.load() == 1); + EXPECT_TRUE(count.load() == 1); int sleep2 = 100; ptr->SyncDispatch(std::make_shared([&count, sleep = sleep2]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 1); + EXPECT_TRUE(index == 1); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); })); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); int sleep3 = 1000; ptr->SyncDispatch(std::make_shared([&count, sleep = sleep3]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 2); + EXPECT_TRUE(index == 2); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); })); - ASSERT_TRUE(count.load() == 3); + EXPECT_TRUE(count.load() == 3); long wait = 1000; GTEST_LOG_(INFO) << ("wait for " + std::to_string(wait)); @@ -182,36 +182,36 @@ HWTEST(SpecTaskDispatcherTest, AsyncDispatch_0100, Function | MediumTest | Level // task runs synchronized // use elapsed time to identify a task. std::atomic count(0); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep1 = 2000; ptr->AsyncDispatch(std::make_shared([&count, sleep = sleep1]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 0); + EXPECT_TRUE(index == 0); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); })); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep2 = 1000; ptr->AsyncDispatch(std::make_shared([&count, sleep = sleep2]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 1); + EXPECT_TRUE(index == 1); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); })); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep3 = 1000; ptr->AsyncDispatch(std::make_shared([&count, sleep = sleep3]() { auto time = std::chrono::milliseconds(sleep); std::this_thread::sleep_for(time); int index = count.fetch_add(1); - ASSERT_TRUE(index == 2); + EXPECT_TRUE(index == 2); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); })); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); { long wait = 100; @@ -223,28 +223,28 @@ HWTEST(SpecTaskDispatcherTest, AsyncDispatch_0100, Function | MediumTest | Level GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 1); + EXPECT_TRUE(count.load() == 1); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 3); + EXPECT_TRUE(count.load() == 3); } GTEST_LOG_(INFO) << "AsyncDispatch_0100 end"; @@ -283,31 +283,31 @@ HWTEST(SpecTaskDispatcherTest, DelayDispatch_0100, Function | MediumTest | Level ptr->DelayDispatch(std::make_shared([&count, sleep = sleep1]() { // execute second int index = count.fetch_add(1); - ASSERT_TRUE(index == 2); + EXPECT_TRUE(index == 2); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); }), sleep1); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep2 = 1000; ptr->DelayDispatch(std::make_shared([&count, sleep = sleep2]() { // execute first int index = count.fetch_add(1); - ASSERT_TRUE(index == 0 || index == 1); + EXPECT_TRUE(index == 0 || index == 1); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); }), sleep2); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); int sleep3 = 1000; ptr->DelayDispatch(std::make_shared([&count, sleep = sleep3]() { // execute first int index = count.fetch_add(1); - ASSERT_TRUE(index == 0 || index == 1); + EXPECT_TRUE(index == 0 || index == 1); APP_LOGD("task %{public}d end, elapsed %{public}d ms", index, sleep); }), sleep3); - ASSERT_TRUE(count.load() == 0); + EXPECT_TRUE(count.load() == 0); { long wait = 100; @@ -319,21 +319,21 @@ HWTEST(SpecTaskDispatcherTest, DelayDispatch_0100, Function | MediumTest | Level GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); } { long wait = 500; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 2); + EXPECT_TRUE(count.load() == 2); } { long wait = 1000; GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - ASSERT_TRUE(count.load() == 3); + EXPECT_TRUE(count.load() == 3); } GTEST_LOG_(INFO) << "DelayDispatch_0100 end"; } diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp index 8b87a0fa41fde9c8d75c011eeb585310908ba848..bad87ebc868d662ec5f7a0ad2aed50a217f6d5fe 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/task_dispatcher_context_test/task_dispatcher_context_test.cpp @@ -57,7 +57,7 @@ HWTEST(TaskDispatcherContextTest, TaskDispatcherContext_0100, Function | MediumT GTEST_LOG_(INFO) << "TaskDispatcherContext_0100 start"; std::shared_ptr taskDispatcherContext = std::make_shared(); std::shared_ptr config = taskDispatcherContext->GetWorkerPoolConfig(); - ASSERT_EQ(config.get()->GetMaxThreadCount(), 32); + EXPECT_EQ(config.get()->GetMaxThreadCount(), 32); GTEST_LOG_(INFO) << "TaskDispatcherContext_0100 end"; } @@ -76,7 +76,7 @@ HWTEST(TaskDispatcherContextTest, TaskDispatcherContext_0200, Function | MediumT std::make_shared(testTaskExecutor); std::map workerThreadsInfo = taskDispatcherContext->GetWorkerThreadsInfo(); bool flag = (workerThreadsInfo.size() == 0); - ASSERT_TRUE(flag); + EXPECT_TRUE(flag); GTEST_LOG_(INFO) << "TaskDispatcherContext_0200 end"; } @@ -91,7 +91,7 @@ HWTEST(TaskDispatcherContextTest, GetWorkerPoolConfig_0100, Function | MediumTes GTEST_LOG_(INFO) << "GetWorkerPoolConfig_0100 start"; std::shared_ptr taskDispatcherContext = std::make_shared(); std::shared_ptr config = taskDispatcherContext->GetWorkerPoolConfig(); - ASSERT_EQ(config.get()->GetMaxThreadCount(), 32); + EXPECT_EQ(config.get()->GetMaxThreadCount(), 32); GTEST_LOG_(INFO) << "GetWorkerPoolConfig_0100 end"; } /** @@ -107,7 +107,7 @@ HWTEST(TaskDispatcherContextTest, GetWorkerThreadsInfo_0100, Function | MediumTe std::shared_ptr taskDispatcherContext = std::make_shared(nullptr); std::map workerThreadsInfo = taskDispatcherContext->GetWorkerThreadsInfo(); bool flag = (workerThreadsInfo.size() == 0); - ASSERT_TRUE(flag); + EXPECT_TRUE(flag); GTEST_LOG_(INFO) << "GetWorkerThreadsInfo_0100 end"; } /** @@ -125,7 +125,7 @@ HWTEST(TaskDispatcherContextTest, GetWorkerThreadsInfo_0200, Function | MediumTe std::make_shared(testTaskExecutor); std::map workerThreadsInfo = taskDispatcherContext->GetWorkerThreadsInfo(); bool flag = (workerThreadsInfo.size() == 0); - ASSERT_TRUE(flag); + EXPECT_TRUE(flag); GTEST_LOG_(INFO) << "TaskDispatcherContext_0200 end"; } /** @@ -143,7 +143,7 @@ HWTEST(TaskDispatcherContextTest, CreateSerialDispatcher_0100, Function | Medium TaskPriority taskPriority = TaskPriority::DEFAULT; std::shared_ptr ptrSerialTaskDispatcher = taskDispatcherContext->CreateSerialDispatcher(dispatcherName, taskPriority); - ASSERT_EQ(ptrSerialTaskDispatcher->GetDispatcherName(), dispatcherName); + EXPECT_EQ(ptrSerialTaskDispatcher->GetDispatcherName(), dispatcherName); GTEST_LOG_(INFO) << "CreateSerialDispatcher_0100 end"; } /** @@ -168,10 +168,10 @@ HWTEST(TaskDispatcherContextTest, GetSerialDispatchers_0100, Function | MediumTe std::map, std::string> serialDispatchers = taskDispatcherContext->GetSerialDispatchers(); bool flag = (serialDispatchers.size() == 2); - ASSERT_TRUE(flag); + EXPECT_TRUE(flag); std::map, std::string>::iterator iter; for (iter = serialDispatchers.begin(); iter != serialDispatchers.end(); iter++) { - ASSERT_EQ(iter->second, dispatcherName); + EXPECT_EQ(iter->second, dispatcherName); } GTEST_LOG_(INFO) << "GetSerialDispatchers_0100 end"; } @@ -189,7 +189,7 @@ HWTEST(TaskDispatcherContextTest, CreateParallelDispatcher_0100, Function | Medi TaskPriority taskPriority = TaskPriority::HIGH; std::shared_ptr ptrSerialTaskDispatcher = taskDispatcherContext->CreateParallelDispatcher(dispatcherName, taskPriority); - ASSERT_EQ(ptrSerialTaskDispatcher->GetPriority(), taskPriority); + EXPECT_EQ(ptrSerialTaskDispatcher->GetPriority(), taskPriority); GTEST_LOG_(INFO) << "CreateParallelDispatcher_0100 end"; } @@ -252,7 +252,7 @@ HWTEST(TaskDispatcherContextTest, GetWaitingTasksCount_0100, Function | MediumTe const std::shared_ptr testTaskExecutor = nullptr; std::shared_ptr taskDispatcherContext = std::make_shared(testTaskExecutor); - ASSERT_EQ(taskDispatcherContext->GetWaitingTasksCount(), 0); + EXPECT_EQ(taskDispatcherContext->GetWaitingTasksCount(), 0); GTEST_LOG_(INFO) << "GetWaitingTasksCount_0100 end"; } @@ -269,7 +269,7 @@ HWTEST(TaskDispatcherContextTest, GetWaitingTasksCount_0200, Function | MediumTe const std::shared_ptr testTaskExecutor = std::make_shared(config); std::shared_ptr taskDispatcherContext = std::make_shared(testTaskExecutor); - ASSERT_EQ(taskDispatcherContext->GetWaitingTasksCount(), 0); + EXPECT_EQ(taskDispatcherContext->GetWaitingTasksCount(), 0); GTEST_LOG_(INFO) << "GetWaitingTasksCount_0200 end"; } /** @@ -285,6 +285,6 @@ HWTEST(TaskDispatcherContextTest, GetTaskCounter_0100, Function | MediumTest | L const std::shared_ptr testTaskExecutor = std::make_shared(config); std::shared_ptr taskDispatcherContext = std::make_shared(testTaskExecutor); - ASSERT_EQ(taskDispatcherContext->GetTaskCounter(), 0); + EXPECT_EQ(taskDispatcherContext->GetTaskCounter(), 0); GTEST_LOG_(INFO) << "GetTaskCounter_0100 end"; } \ No newline at end of file diff --git a/interfaces/innerkits/test/mock/include/test.cpp b/interfaces/innerkits/test/mock/include/test.cpp deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp index 110f9356de2713a5cdeeaa353a981eeaa2dc8d0a..6abe4204c16ef42f57e99d1b945f2e8798c004ca 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp @@ -68,7 +68,6 @@ std::shared_ptr GlobalTaskDispatcherModuleTest::GetMtGlobalTaskD HWTEST_F(GlobalTaskDispatcherModuleTest, GetMtGlobalTaskDispatcherTest_001, TestSize.Level1) { auto name = std::string("GetMtGlobalTaskDispatcherTest_001"); - // TaskDispatcherContext context; GTEST_LOG_(INFO) << name + " start"; TaskPriority defaultPriority = TaskPriority::DEFAULT; std::shared_ptr defaultPtr1 = GetMtGlobalTaskDispatcher(defaultPriority); diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/parallel_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/parallel_task_dispatcher_module_test.cpp index 159c241aec342f78a405744892f831e7939af6c0..2724e7393b710068bcde8542427fe967ce8d86a6 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/parallel_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/parallel_task_dispatcher_module_test/parallel_task_dispatcher_module_test.cpp @@ -300,15 +300,11 @@ HWTEST_F(ParallelTaskDispatcherModuleTest, ParallelTaskDispatcher_DelayDispatchT GTEST_LOG_(INFO) << name << " Runnable2"; }), sleep2); - // printf("111111111111111111111111111111111111111111111111111111111111111111"); EXPECT_TRUE(count.load() < 2); long wait = 1000; auto time = std::chrono::milliseconds(wait); std::this_thread::sleep_for(time); - // printf("222222222222222222222222222222222222222222222222222222222222222222"); EXPECT_TRUE(count.load() == 2); - // printf("33333333333333333333333333333333333333333333333333333333333333333"); - // printf("context use count:%d", context.use_count()); GTEST_LOG_(INFO) << name << " end"; } diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp index efebb9c2a9b9a22c1f0d7a00eccefa33ca2aaac7..b267e283e1d06a68bc2b96c8894b586061cc52f0 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp @@ -187,16 +187,14 @@ HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_AsyncDispatchTest_ const int total = 300; std::atomic count(0); long wait = 100; - int period = 10; for (int i = 0; i < total; i++) { - ptr->AsyncDispatch(std::make_shared([&count, &period, &name]() { - int sleep = std::rand() % period; - auto time = std::chrono::milliseconds(sleep); + ptr->AsyncDispatch(std::make_shared([&count, &name]() { + auto time = std::chrono::milliseconds(1); std::this_thread::sleep_for(time); int index = count.fetch_add(1); GTEST_LOG_(INFO) << "SerialTaskDispatcher_AsyncDispatchTest_002 task" + std::to_string(index) + "end"; })); - wait += period; + wait += 1; } EXPECT_TRUE(count.load() < total); auto time = std::chrono::milliseconds(wait + 1000); diff --git a/kits/BUILD.gn b/kits/BUILD.gn index 38188317539738b3a8438e62ba5e4cf09bc54a96..5cbdd086c505b1f47b3de9fdecda120728ae9221 100755 --- a/kits/BUILD.gn +++ b/kits/BUILD.gn @@ -105,7 +105,6 @@ ohos_shared_library("appkit_native") { sources = [ "$SUBSYSTEM_DIR/kits/appkit/native/app/src/ability_manager.cpp", "$SUBSYSTEM_DIR/kits/appkit/native/app/src/ability_record_mgr.cpp", - "$SUBSYSTEM_DIR/kits/appkit/native/app/src/ability_start_setting.cpp", "$SUBSYSTEM_DIR/kits/appkit/native/app/src/app_loader.cpp", "$SUBSYSTEM_DIR/kits/appkit/native/app/src/application_context.cpp", "$SUBSYSTEM_DIR/kits/appkit/native/app/src/application_env.cpp", @@ -138,7 +137,6 @@ ohos_shared_library("appkit_native") { public_deps = [ "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr" ] - external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/kits/appkit/napi/bundlemgr/BUILD.gn b/kits/appkit/napi/bundlemgr/BUILD.gn index e78938a77dd9d1fc7d1ab974c20dc68ec2a48470..20f2273cc18ac494275131d0faf73b38c03651b6 100644 --- a/kits/appkit/napi/bundlemgr/BUILD.gn +++ b/kits/appkit/napi/bundlemgr/BUILD.gn @@ -17,6 +17,7 @@ ohos_shared_library("bundle") { include_dirs = [ "//foundation/ace/napi/interfaces/kits", "//third_party/node/src", + "//third_party/libuv/include", "//foundation/aafwk/standard/services/common/include", "//utils/system/safwk/native/include", "./", @@ -26,6 +27,7 @@ ohos_shared_library("bundle") { "bundle_mgr.cpp", "installer_callback.cpp", "native_module.cpp", + "permission_callback.cpp", ] deps = [ diff --git a/kits/appkit/napi/bundlemgr/bundle_mgr.cpp b/kits/appkit/napi/bundlemgr/bundle_mgr.cpp index 2e5350e9effb508227cfd85e19a3e14ad5f89395..97c625351fd2a274a4d8b030bffe43906873e92b 100644 --- a/kits/appkit/napi/bundlemgr/bundle_mgr.cpp +++ b/kits/appkit/napi/bundlemgr/bundle_mgr.cpp @@ -21,6 +21,9 @@ #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "installer_callback.h" +#include "permission_callback.h" +#include "ipc_skeleton.h" +#include "bundle_constants.h" using namespace OHOS; using namespace OHOS::AAFwk; @@ -36,12 +39,6 @@ constexpr size_t ARGS_SIZE_FOUR = 4; constexpr int32_t DEFAULT_INT32 = 0; constexpr int32_t PARAM0 = 0; constexpr int32_t PARAM1 = 1; -constexpr int32_t PARAM2 = 2; -constexpr int32_t NAPI_RETURN_FAILED = -1; -constexpr int32_t NAPI_RETURN_ZERO = 0; -constexpr int32_t NAPI_RETURN_ONE = 1; -constexpr int32_t NAPI_RETURN_TWO = 2; -constexpr int32_t NAPI_RETURN_THREE = 3; constexpr int32_t CODE_SUCCESS = 0; constexpr int32_t CODE_FAILED = -1; enum class InstallErrorCode { @@ -62,6 +59,24 @@ enum class InstallErrorCode { STATUS_BMS_SERVICE_ERROR = 0x41 }; +const std::string PERMISSION_CHANGE = "permissionChange"; +const std::string ANY_PERMISSION_CHANGE = "anyPermissionChange"; + +std::mutex permissionsCallbackMutex; +std::mutex anyPermissionsCallbackMutex; + +struct PermissionsKey { + napi_ref callback = 0; + std::vector uids; + bool operator<(const PermissionsKey &other) const + { + return this->callback < other.callback; + } +}; + +std::map> permissionsCallback; +std::map> anyPermissionsCallback; + } // namespace napi_value g_classBundleInstaller; @@ -75,6 +90,15 @@ static OHOS::sptr GetBundleMgr() return OHOS::iface_cast(remoteObject); } +static bool CheckIsSystemApp() +{ + int32_t uid = IPCSkeleton::GetCallingUid(); + if (uid >= OHOS::AppExecFwk::Constants::ROOT_UID && uid <= OHOS::AppExecFwk::Constants::MAX_SYS_UID) { + return true; + } + return false; +} + static void ConvertApplicationInfo(napi_env env, napi_value objAppInfo, const ApplicationInfo &appInfo) { napi_value nName; @@ -119,9 +143,12 @@ static void ConvertApplicationInfo(napi_env env, napi_value objAppInfo, const Ap NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.process.c_str(), NAPI_AUTO_LENGTH, &nProcess)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "process", nProcess)); - napi_value nEntryDir; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, appInfo.entryDir.c_str(), NAPI_AUTO_LENGTH, &nEntryDir)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "entryDir", nEntryDir)); + if (CheckIsSystemApp()) { + napi_value nEntryDir; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, appInfo.entryDir.c_str(), NAPI_AUTO_LENGTH, &nEntryDir)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAppInfo, "entryDir", nEntryDir)); + } napi_value nPermissions; NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nPermissions)); @@ -187,14 +214,15 @@ static void ConvertCustomizeData(napi_env env, napi_value objCustomizeData, cons HILOG_INFO("ConvertCustomizeData value=%{public}s.", customizeData.value.c_str()); napi_value nExtra; NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, customizeData.extra.c_str(), NAPI_AUTO_LENGTH, &nExtra)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objCustomizeData, "value", nExtra)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objCustomizeData, "extra", nExtra)); HILOG_INFO("ConvertCustomizeData extra=%{public}s.", customizeData.extra.c_str()); } static void ConvertParameters(napi_env env, napi_value objParameters, const Parameters ¶meters) { napi_value nDescription; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, parameters.description.c_str(), NAPI_AUTO_LENGTH, &nDescription)); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, parameters.description.c_str(), NAPI_AUTO_LENGTH, &nDescription)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objParameters, "description", nDescription)); HILOG_INFO("ConvertParameters parameters.description=%{public}s.", parameters.description.c_str()); napi_value nName; @@ -210,7 +238,8 @@ static void ConvertParameters(napi_env env, napi_value objParameters, const Para static void ConvertResults(napi_env env, napi_value objResults, const Results &results) { napi_value nDescription; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, results.description.c_str(), NAPI_AUTO_LENGTH, &nDescription)); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, results.description.c_str(), NAPI_AUTO_LENGTH, &nDescription)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objResults, "description", nDescription)); HILOG_INFO("ConvertResults results.description=%{public}s.", results.description.c_str()); napi_value nName; @@ -223,7 +252,6 @@ static void ConvertResults(napi_env env, napi_value objResults, const Results &r HILOG_INFO("ConvertResults results.type=%{public}s.", results.type.c_str()); } - static void ConvertMetaData(napi_env env, napi_value objMetaData, const MetaData &metaData) { napi_value nCustomizeDatas; @@ -279,6 +307,16 @@ static void ConvertAbilityInfo(napi_env env, napi_value objAbilityInfo, const Ab env, napi_create_string_utf8(env, abilityInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &nIconPath)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "icon", nIconPath)); + napi_value nsrcPath; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, abilityInfo.srcPath.c_str(), NAPI_AUTO_LENGTH, &nsrcPath)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "srcPath", nsrcPath)); + + napi_value nLaunguage; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, abilityInfo.srcLanguage.c_str(), NAPI_AUTO_LENGTH, &nLaunguage)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "srcLanguage", nLaunguage)); + napi_value nVisible; NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, abilityInfo.visible, &nVisible)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "isVisible", nVisible)); @@ -634,10 +672,12 @@ static void ConvertFormInfo(napi_env env, napi_value objformInfo, const FormInfo static void ConvertShortcutIntent(napi_env env, napi_value objShortcutInfo, const ShortcutIntent &shortcutIntent) { napi_value nTargetBundle; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, shortcutIntent.targetBundle.c_str(), NAPI_AUTO_LENGTH, &nTargetBundle)); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, shortcutIntent.targetBundle.c_str(), NAPI_AUTO_LENGTH, &nTargetBundle)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "targetBundle", nTargetBundle)); napi_value nTargetClass; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, shortcutIntent.targetClass.c_str(), NAPI_AUTO_LENGTH, &nTargetClass)); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, shortcutIntent.targetClass.c_str(), NAPI_AUTO_LENGTH, &nTargetClass)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "targetClass", nTargetClass)); } @@ -659,13 +699,11 @@ static void ConvertShortcutInfos(napi_env env, napi_value objShortcutInfo, const NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "hostAbility", nHostAbility)); napi_value nIcon; - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, shortcutInfo.icon.c_str(), NAPI_AUTO_LENGTH, &nIcon)); + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, shortcutInfo.icon.c_str(), NAPI_AUTO_LENGTH, &nIcon)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "icon", nIcon)); napi_value nLabel; - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, shortcutInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel)); + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, shortcutInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "label", nLabel)); napi_value nDisableMessage; @@ -683,7 +721,7 @@ static void ConvertShortcutInfos(napi_env env, napi_value objShortcutInfo, const napi_value nIsEnables; NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, shortcutInfo.isEnables, &nIsEnables)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "isEnables", nIsEnables)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "isEnabled", nIsEnables)); napi_value nIntents; NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nIntents)); @@ -693,20 +731,92 @@ static void ConvertShortcutInfos(napi_env env, napi_value objShortcutInfo, const ConvertShortcutIntent(env, nIntent, shortcutInfo.intents[idx]); NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nIntents, idx, nIntent)); } - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "intents", nIntents)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objShortcutInfo, "wants", nIntents)); +} + +static void ConvertModuleUsageRecords( + napi_env env, napi_value objModuleUsageRecord, const ModuleUsageRecord &moduleUsageRecord) +{ + napi_value nbundleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, moduleUsageRecord.bundleName.c_str(), NAPI_AUTO_LENGTH, &nbundleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "bundleName", nbundleName)); + HILOG_INFO("ConvertModuleUsageRecords bundleName=%{public}s.", moduleUsageRecord.bundleName.c_str()); + + napi_value nappLabelId; + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleUsageRecord.appLabelId, &nappLabelId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "appLabelId", nappLabelId)); + HILOG_INFO("ConvertModuleUsageRecords appLabelId=%{public}ud.", moduleUsageRecord.appLabelId); + + napi_value nname; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleUsageRecord.name.c_str(), NAPI_AUTO_LENGTH, &nname)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "name", nname)); + HILOG_INFO("ConvertModuleUsageRecords name=%{public}s.", moduleUsageRecord.name.c_str()); + + napi_value nlabelId; + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleUsageRecord.labelId, &nlabelId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "labelId", nlabelId)); + HILOG_INFO("ConvertModuleUsageRecords labelId=%{public}ud.", moduleUsageRecord.labelId); + + napi_value ndescriptionId; + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleUsageRecord.descriptionId, &ndescriptionId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "descriptionId", ndescriptionId)); + HILOG_INFO("ConvertModuleUsageRecords descriptionId=%{public}ud.", moduleUsageRecord.descriptionId); + + napi_value nabilityName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, moduleUsageRecord.abilityName.c_str(), NAPI_AUTO_LENGTH, &nabilityName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "abilityName", nabilityName)); + HILOG_INFO("ConvertModuleUsageRecords abilityName=%{public}s.", moduleUsageRecord.abilityName.c_str()); + + napi_value nabilityLabelId; + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleUsageRecord.abilityLabelId, &nabilityLabelId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "abilityLabelId", nabilityLabelId)); + HILOG_INFO("ConvertModuleUsageRecords abilityLabelId=%{public}ud.", moduleUsageRecord.abilityLabelId); + + napi_value nabilityDescriptionId; + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleUsageRecord.abilityDescriptionId, &nabilityDescriptionId)); + NAPI_CALL_RETURN_VOID( + env, napi_set_named_property(env, objModuleUsageRecord, "abilityDescriptionId", nabilityDescriptionId)); + HILOG_INFO("ConvertModuleUsageRecords abilityDescriptionId=%{public}ud.", moduleUsageRecord.abilityDescriptionId); + + napi_value nabilityIconId; + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleUsageRecord.abilityIconId, &nabilityIconId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "abilityIconId", nabilityIconId)); + HILOG_INFO("ConvertModuleUsageRecords abilityIconId=%{public}ud.", moduleUsageRecord.abilityIconId); + + napi_value nlaunchedCount; + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleUsageRecord.launchedCount, &nlaunchedCount)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "launchedCount", nlaunchedCount)); + HILOG_INFO("ConvertModuleUsageRecords launchedCount=%{public}ud.", moduleUsageRecord.launchedCount); + + napi_value nlastLaunchTime; + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, moduleUsageRecord.lastLaunchTime, &nlastLaunchTime)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "lastLaunchTime", nlastLaunchTime)); + + napi_value nremoved; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, moduleUsageRecord.removed, &nremoved)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objModuleUsageRecord, "isRemoved", nremoved)); + + napi_value ninstallationFreeSupported; + NAPI_CALL_RETURN_VOID( + env, napi_get_boolean(env, moduleUsageRecord.installationFreeSupported, &ninstallationFreeSupported)); + NAPI_CALL_RETURN_VOID(env, + napi_set_named_property(env, objModuleUsageRecord, "installationFreeSupported", ninstallationFreeSupported)); } + static std::string GetStringFromNAPI(napi_env env, napi_value value) { std::string result; size_t size = 0; - if (napi_get_value_string_utf8(env, value, nullptr, NAPI_RETURN_ZERO, &size) != napi_ok) { + if (napi_get_value_string_utf8(env, value, nullptr, 0, &size) != napi_ok) { HILOG_ERROR("can not get string size"); return ""; } - result.reserve(size + NAPI_RETURN_ONE); + result.reserve(size + 1); result.resize(size); - if (napi_get_value_string_utf8(env, value, result.data(), (size + NAPI_RETURN_ONE), &size) != napi_ok) { + if (napi_get_value_string_utf8(env, value, result.data(), (size + 1), &size) != napi_ok) { HILOG_ERROR("can not get string value"); return ""; } @@ -726,7 +836,7 @@ static napi_value ParseInt(napi_env env, int ¶m, napi_value args) param = value; // create result code napi_value result; - status = napi_create_int32(env, NAPI_RETURN_ONE, &result); + status = napi_create_int32(env, 1, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -788,8 +898,8 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); int flag; int userId; - ParseInt(env, flag, argv[PARAM0]); - ParseInt(env, userId, argv[PARAM1]); + ParseInt(env, flag, argv[0]); + ParseInt(env, userId, argv[1]); ApplicationFlag applicationFlag = ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS; if (flag == static_cast(ApplicationFlag::GET_BASIC_APPLICATION_INFO)) { applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; @@ -804,7 +914,7 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -837,8 +947,16 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetApplicationInfos promise."); @@ -871,6 +989,15 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -934,7 +1061,7 @@ static napi_value ParseWant(napi_env env, Want &want, napi_value args) // create result code napi_value result; - status = napi_create_int32(env, NAPI_RETURN_ONE, &result); + status = napi_create_int32(env, 1, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -971,7 +1098,7 @@ static napi_value ParseQueryParameter(napi_env env, QueryParameter &queryParamet HILOG_INFO("ParseQueryParameter userId=%{public}s.", queryParameter.userId.c_str()); // create result code napi_value result; - status = napi_create_int32(env, NAPI_RETURN_ONE, &result); + status = napi_create_int32(env, 1, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -988,12 +1115,12 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); Want want; - ParseWant(env, want, argv[PARAM0]); + ParseWant(env, want, argv[0]); HILOG_INFO("After ParseWant action=%{public}s.", want.GetAction().c_str()); HILOG_INFO("After ParseWant bundleName=%{public}s.", want.GetElement().GetBundleName().c_str()); HILOG_INFO("After ParseWant abilityName=%{public}s.", want.GetElement().GetAbilityName().c_str()); QueryParameter queryParameter; - ParseQueryParameter(env, queryParameter, argv[PARAM1]); + ParseQueryParameter(env, queryParameter, argv[1]); AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = new AsyncAbilityInfoCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr, .want = want}; @@ -1002,7 +1129,7 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "QueryAbilityInfo", NAPI_AUTO_LENGTH, &resourceName); @@ -1038,8 +1165,16 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("QueryAbilityInfo promise."); @@ -1071,6 +1206,16 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } + return promise; } } @@ -1096,7 +1241,7 @@ static napi_value ParseString(napi_env env, std::string ¶m, napi_value args) HILOG_INFO("param=%{public}s.", param.c_str()); // create result code napi_value result; - status = napi_create_int32(env, NAPI_RETURN_ONE, &result); + status = napi_create_int32(env, 1, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -1113,9 +1258,9 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) int flag; int userId; std::string bundleName; - ParseString(env, bundleName, argv[PARAM0]); - ParseInt(env, flag, argv[PARAM1]); - ParseInt(env, userId, argv[PARAM2]); + ParseString(env, bundleName, argv[0]); + ParseInt(env, flag, argv[1]); + ParseInt(env, userId, argv[2]); ApplicationFlag applicationFlag = ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS; if (flag == static_cast(ApplicationFlag::GET_BASIC_APPLICATION_INFO)) { applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; @@ -1132,7 +1277,7 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_THREE], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_THREE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_THREE], 1, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "NAPI_GetApplicationInfoCallBack", NAPI_AUTO_LENGTH, &resourceName); @@ -1175,8 +1320,16 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetApplicationInfo promise."); @@ -1216,6 +1369,15 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -1265,7 +1427,7 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) void *data = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); int flag; - ParseInt(env, flag, argv[PARAM0]); + ParseInt(env, flag, argv[0]); BundleFlag bundleFlag = BundleFlag::GET_BUNDLE_WITH_ABILITIES; if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; @@ -1279,7 +1441,7 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], 1, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -1312,8 +1474,17 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("BundleMgr::GetBundleInfos promise."); @@ -1345,9 +1516,19 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } + static bool InnerGetBundleInfo( napi_env env, const std::string &bundleName, const BundleFlag bundleFlag, BundleInfo &bundleInfo) { @@ -1374,8 +1555,8 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string bundleName; int flag; - ParseString(env, bundleName, argv[PARAM0]); - ParseInt(env, flag, argv[PARAM1]); + ParseString(env, bundleName, argv[0]); + ParseInt(env, flag, argv[1]); BundleFlag bundleFlag = BundleFlag::GET_BUNDLE_WITH_ABILITIES; if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; @@ -1388,7 +1569,7 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "NAPI_InnerGetBundleInfo", NAPI_AUTO_LENGTH, &resourceName); @@ -1424,8 +1605,16 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetBundleinfo promise."); @@ -1458,6 +1647,15 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -1488,8 +1686,8 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string hapFilePath; int flag; - ParseString(env, hapFilePath, argv[PARAM0]); - ParseInt(env, flag, argv[PARAM1]); + ParseString(env, hapFilePath, argv[0]); + ParseInt(env, flag, argv[1]); BundleFlag bundleFlag = BundleFlag::GET_BUNDLE_WITH_ABILITIES; if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; @@ -1502,7 +1700,7 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "NAPI_GetBundleArchiveInfo", NAPI_AUTO_LENGTH, &resourceName); @@ -1537,8 +1735,16 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetBundleArchiveInfo promise."); @@ -1571,6 +1777,15 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -1659,7 +1874,7 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); std::string permissionName; - ParseString(env, permissionName, argv[PARAM0]); + ParseString(env, permissionName, argv[0]); AsyncPermissionDefCallbackInfo *asyncCallbackInfo = new AsyncPermissionDefCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .permissionName = permissionName}; @@ -1668,7 +1883,7 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], 1, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "GetPermissionDef", NAPI_AUTO_LENGTH, &resourceName); @@ -1703,8 +1918,16 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { napi_deferred deferred; @@ -1735,6 +1958,15 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -1779,7 +2011,7 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) size_t argc = ARGS_SIZE_ONE; napi_value argv[ARGS_SIZE_ONE] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - HILOG_INFO("argc = [%{public}zu]", argc); + HILOG_INFO("argc = [%{public}d]", argc); AsyncGetBundleInstallerCallbackInfo *asyncCallbackInfo = new AsyncGetBundleInstallerCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; @@ -1787,9 +2019,9 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) if (argc > (ARGS_SIZE_ONE - CALLBACK_SIZE)) { HILOG_INFO("GetBundleInstaller asyncCallback."); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[PARAM0], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); + napi_create_reference(env, argv[0], 1, &asyncCallbackInfo->callback); napi_value resourceName; napi_create_string_latin1(env, "GetBundleInstaller", NAPI_AUTO_LENGTH, &resourceName); @@ -1818,8 +2050,16 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { napi_deferred deferred; @@ -1846,6 +2086,15 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -1874,6 +2123,16 @@ static napi_value ParseInstallParam(napi_env env, InstallParam &installParam, na installParam.userId = userId; HILOG_INFO("ParseInstallParam userId=%{public}d.", installParam.userId); + property = nullptr; + status = napi_get_named_property(env, installProp, "noCheckSignature", &property); + NAPI_ASSERT(env, status == napi_ok, "property noCheckSignature incorrect!"); + napi_typeof(env, property, &valueType); + NAPI_ASSERT(env, valueType == napi_boolean, "property type mismatch!"); + bool noCheckSignature = false; + NAPI_CALL(env, napi_get_value_bool(env, property, &noCheckSignature)); + installParam.noCheckSignature = noCheckSignature; + HILOG_INFO("ParseInstallParam noCheckSignature=%{public}d.", installParam.noCheckSignature); + property = nullptr; status = napi_get_named_property(env, installProp, "isKeepData", &property); NAPI_ASSERT(env, status == napi_ok, "property isKeepData incorrect!"); @@ -1885,7 +2144,7 @@ static napi_value ParseInstallParam(napi_env env, InstallParam &installParam, na HILOG_INFO("ParseInstallParam isKeepData=%{public}d.", installParam.isKeepData); // create result code napi_value result; - status = napi_create_int32(env, NAPI_RETURN_ONE, &result); + status = napi_create_int32(env, 1, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -1899,7 +2158,7 @@ static napi_value ParseStringArray(napi_env env, std::vector &hapFi napi_valuetype valueAryType = napi_undefined; NAPI_CALL(env, napi_is_array(env, args, &isArray)); NAPI_CALL(env, napi_get_array_length(env, args, &arrayLength)); - HILOG_INFO("ParseStringArray args is array, length=%{public}d", arrayLength); + HILOG_INFO("ParseStringArray args is array, length=%{public}ud", arrayLength); for (uint32_t j = 0; j < arrayLength; j++) { NAPI_CALL(env, napi_get_element(env, args, j, &valueAry)); @@ -1913,7 +2172,7 @@ static napi_value ParseStringArray(napi_env env, std::vector &hapFi // create result code napi_value result; napi_status status; - status = napi_create_int32(env, NAPI_RETURN_ONE, &result); + status = napi_create_int32(env, 1, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -1978,17 +2237,21 @@ static void ConvertInstallResult(InstallResult &installResult) installResult.resultCode = static_cast(InstallErrorCode::STATUS_INSTALL_FAILURE_STORAGE); installResult.resultMsg = "STATUS_INSTALL_FAILURE_STORAGE"; break; - case static_cast(IStatusReceiver::ERR_UNINSTALL_SYSTEM_APP_ERROR): - case static_cast(IStatusReceiver::ERR_UNINSTALL_KILLING_APP_ERROR): - installResult.resultCode = static_cast(InstallErrorCode::STATUS_UNINSTALL_FAILURE_CONFLICT); - installResult.resultMsg = "STATUS_UNINSTALL_FAILURE_CONFLICT"; - break; case static_cast(IStatusReceiver::ERR_UNINSTALL_INVALID_NAME): case static_cast(IStatusReceiver::ERR_UNINSTALL_PARAM_ERROR): case static_cast(IStatusReceiver::ERR_UNINSTALL_PERMISSION_DENIED): - installResult.resultCode = static_cast(InstallErrorCode::STATUS_UNINSTALL_FAILURE_ABORTED); - installResult.resultMsg = "STATUS_UNINSTALL_FAILURE_ABORTED"; - break; + if (CheckIsSystemApp()) { + installResult.resultCode = static_cast(InstallErrorCode::STATUS_UNINSTALL_FAILURE_ABORTED); + installResult.resultMsg = "STATUS_UNINSTALL_FAILURE_ABORTED"; + break; + } + case static_cast(IStatusReceiver::ERR_UNINSTALL_SYSTEM_APP_ERROR): + case static_cast(IStatusReceiver::ERR_UNINSTALL_KILLING_APP_ERROR): + if (CheckIsSystemApp()) { + installResult.resultCode = static_cast(InstallErrorCode::STATUS_UNINSTALL_FAILURE_CONFLICT); + installResult.resultMsg = "STATUS_UNINSTALL_FAILURE_CONFLICT"; + break; + } case static_cast(IStatusReceiver::ERR_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR): case static_cast(IStatusReceiver::ERR_UNINSTALL_MISSING_INSTALLED_BUNDLE): case static_cast(IStatusReceiver::ERR_UNINSTALL_MISSING_INSTALLED_MODULE): @@ -2013,9 +2276,9 @@ napi_value Install(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); std::vector bundleFilePaths; - ParseStringArray(env, bundleFilePaths, argv[PARAM0]); + ParseStringArray(env, bundleFilePaths, argv[0]); InstallParam installParam; - ParseInstallParam(env, installParam, argv[PARAM1]); + ParseInstallParam(env, installParam, argv[1]); AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ .env = env, .asyncWork = nullptr, @@ -2029,7 +2292,7 @@ napi_value Install(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); + napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback); napi_value resourceName; napi_create_string_latin1(env, "Install", NAPI_AUTO_LENGTH, &resourceName); @@ -2074,8 +2337,16 @@ napi_value Install(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { napi_deferred deferred; @@ -2116,6 +2387,15 @@ napi_value Install(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -2156,9 +2436,9 @@ napi_value Uninstall(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); HILOG_INFO("argc = [%{public}zu]", argc); std::string bundleName; - ParseString(env, bundleName, argv[PARAM0]); + ParseString(env, bundleName, argv[0]); InstallParam installParam; - ParseInstallParam(env, installParam, argv[PARAM1]); + ParseInstallParam(env, installParam, argv[1]); AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ .env = env, .asyncWork = nullptr, @@ -2172,7 +2452,7 @@ napi_value Uninstall(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); + napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback); napi_value resourceName; napi_create_string_latin1(env, "Uninstall", NAPI_AUTO_LENGTH, &resourceName); @@ -2216,9 +2496,16 @@ napi_value Uninstall(napi_env env, napi_callback_info info) &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); - + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { napi_deferred deferred; @@ -2257,6 +2544,15 @@ napi_value Uninstall(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -2315,9 +2611,9 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info) napi_value resourceName; NAPI_CALL(env, napi_create_string_latin1(env, "GetAllFormsInfo", NAPI_AUTO_LENGTH, &resourceName)); napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[PARAM0], &valuetype); + napi_typeof(env, argv[0], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[PARAM0], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[0], 1, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2349,8 +2645,17 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetFormInfos promise."); @@ -2382,6 +2687,15 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -2409,8 +2723,8 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); std::string bundleName; std::string moduleName; - ParseString(env, bundleName, argv[PARAM0]); - ParseString(env, moduleName, argv[PARAM1]); + ParseString(env, bundleName, argv[0]); + ParseString(env, moduleName, argv[1]); AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByModuleCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .moduleName = moduleName}; @@ -2421,7 +2735,7 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2454,8 +2768,16 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetFormsInfoByModule promise."); @@ -2488,6 +2810,15 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -2514,7 +2845,7 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); std::string bundleName; - ParseString(env, bundleName, argv[PARAM0]); + ParseString(env, bundleName, argv[0]); AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByAppCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; @@ -2525,7 +2856,7 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], 1, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2558,8 +2889,16 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetFormsInfoByApp promise."); @@ -2591,11 +2930,21 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } -static void ProcessShortcutInfos(napi_env env, napi_value result, const std::vector &shortcutInfos) +static void ProcessShortcutInfos( + napi_env env, napi_value result, const std::vector &shortcutInfos) { if (shortcutInfos.size() > 0) { HILOG_INFO("-----ShortcutInfos is not null-----"); @@ -2614,14 +2963,15 @@ static void ProcessShortcutInfos(napi_env env, napi_value result, const std::vec } } -static bool InnerGetShortcutInfos(napi_env env, const std::string &bundleName, std::vector &shortcutInfos) +static bool InnerGetShortcutInfos( + napi_env env, const std::string &bundleName, std::vector &shortcutInfos) { auto iBundleMgr = GetBundleMgr(); if (!iBundleMgr) { HILOG_ERROR("can not get iBundleMgr"); return false; } - return iBundleMgr-> GetShortcutInfos(bundleName, shortcutInfos); + return iBundleMgr->GetShortcutInfos(bundleName, shortcutInfos); } /** * Promise and async callback @@ -2635,7 +2985,7 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); std::string bundleName; - ParseString(env, bundleName, argv[PARAM0]); + ParseString(env, bundleName, argv[0]); AsyncShortcutInfosCallbackInfo *asyncCallbackInfo = new AsyncShortcutInfosCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; if (argc > (ARGS_SIZE_TWO - CALLBACK_SIZE)) { @@ -2645,7 +2995,7 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], 1, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2678,8 +3028,16 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } napi_value result; - NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); + NAPI_CALL(env, napi_create_int32(env, 1, &result)); return result; } else { HILOG_INFO("GetShortcutInfos promise."); @@ -2711,6 +3069,611 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) (void *)asyncCallbackInfo, &asyncCallbackInfo->asyncWork); napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } + return promise; + } +} + +static void ProcessModuleUsageRecords( + napi_env env, napi_value result, const std::vector &moduleUsageRecords) +{ + if (moduleUsageRecords.size() > 0) { + HILOG_INFO("-----moduleUsageRecords is not null-----"); + size_t index = 0; + for (const auto &item : moduleUsageRecords) { + HILOG_INFO("bundleName{%s} ", item.bundleName.c_str()); + HILOG_INFO("abilityName{%s} ", item.abilityName.c_str()); + napi_value objModuleUsageRecord; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objModuleUsageRecord)); + ConvertModuleUsageRecords(env, objModuleUsageRecord, item); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, objModuleUsageRecord)); + index++; + } + } else { + HILOG_INFO("-----moduleUsageRecords is null-----"); + } +} + +static bool InnerGetModuleUsageRecords( + napi_env env, const int32_t number, std::vector &moduleUsageRecords) +{ + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + HILOG_ERROR("can not get iBundleMgr"); + return false; + } + return iBundleMgr->GetModuleUsageRecords(number, moduleUsageRecords); +} +/** + * Promise and async callback + */ +napi_value GetModuleUsageRecords(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + napi_value thisArg; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); + int number; + ParseInt(env, number, argv[0]); + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = new AsyncModuleUsageRecordsCallbackInfo{ + .env = env, .asyncWork = nullptr, .deferred = nullptr, .number = number}; + if (argc > (ARGS_SIZE_TWO - CALLBACK_SIZE)) { + HILOG_INFO("GetModuleUsageRecords asyncCallback."); + napi_value resourceName; + NAPI_CALL(env, napi_create_string_latin1(env, "GetModuleUsageRecords", NAPI_AUTO_LENGTH, &resourceName)); + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], 1, &asyncCallbackInfo->callback)); + + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = (AsyncModuleUsageRecordsCallbackInfo *)data; + asyncCallbackInfo->ret = + InnerGetModuleUsageRecords(env, asyncCallbackInfo->number, asyncCallbackInfo->moduleUsageRecords); + }, + [](napi_env env, napi_status status, void *data) { + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = (AsyncModuleUsageRecordsCallbackInfo *)data; + napi_value result[ARGS_SIZE_TWO] = {0}; + napi_value callback = 0; + napi_value undefined = 0; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + napi_create_array(env, &result[PARAM1]); + ProcessModuleUsageRecords(env, result[PARAM1], asyncCallbackInfo->moduleUsageRecords); + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->ret ? CODE_SUCCESS : CODE_FAILED); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_call_function(env, undefined, callback, ARGS_SIZE_TWO, &result[PARAM0], &callResult); + + if (asyncCallbackInfo->callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("GetModuleUsageRecords promise."); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, "GetModuleUsageRecords", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = (AsyncModuleUsageRecordsCallbackInfo *)data; + InnerGetModuleUsageRecords(env, asyncCallbackInfo->number, asyncCallbackInfo->moduleUsageRecords); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("=================load================="); + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = (AsyncModuleUsageRecordsCallbackInfo *)data; + napi_value result; + napi_create_array(env, &result); + ProcessModuleUsageRecords(env, result, asyncCallbackInfo->moduleUsageRecords); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } + return promise; + } +} + +static bool InnerRegisterAllPermissionsChanged(napi_env env, napi_ref callbackRef) +{ + HILOG_INFO("InnerRegisterAllPermissionsChanged begin"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + HILOG_ERROR("can not get iBundleMgr"); + return false; + } + OHOS::sptr callback = new PermissionCallback(env, callbackRef); + if (!callback) { + HILOG_ERROR("callback nullptr"); + return false; + } + auto result = iBundleMgr->RegisterAllPermissionsChanged(callback); + if (!result) { + HILOG_ERROR("RegisterAllPermissionsChanged call error"); + return false; + } + std::lock_guard lock(anyPermissionsCallbackMutex); + auto ret = anyPermissionsCallback.emplace(callbackRef, callback); + if (!ret.second) { + HILOG_ERROR("RegisterAllPermissionsChanged emplace failed"); + return false; + } + HILOG_INFO("InnerRegisterAllPermissionsChanged end"); + return true; +} + +static napi_value ParseInt32Array(napi_env env, std::vector &uids, napi_value args) +{ + HILOG_INFO("Parseint32Array called"); + bool isArray = false; + uint32_t arrayLength = 0; + napi_value valueAry = 0; + napi_valuetype valueAryType = napi_undefined; + NAPI_CALL(env, napi_is_array(env, args, &isArray)); + NAPI_CALL(env, napi_get_array_length(env, args, &arrayLength)); + HILOG_INFO("Parseint32Array args is array, length=%{public}ud", arrayLength); + + for (uint32_t j = 0; j < arrayLength; j++) { + NAPI_CALL(env, napi_get_element(env, args, j, &valueAry)); + NAPI_CALL(env, napi_typeof(env, valueAry, &valueAryType)); + int uid; + ParseInt(env, uid, valueAry); + uids.emplace_back(uid); + } + // create result code + napi_value result; + napi_status status; + status = napi_create_int32(env, 1, &result); + NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); + return result; +} + +static bool InnerRegisterPermissionsChanged(napi_env env, const std::vector &uids, napi_ref callbackRef) +{ + HILOG_INFO("InnerRegisterPermissionsChanged begin"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + HILOG_ERROR("can not get iBundleMgr"); + return false; + } + OHOS::sptr callback = new PermissionCallback(env, callbackRef); + if (!callback) { + HILOG_ERROR("callback nullptr"); + return false; + } + auto result = iBundleMgr->RegisterPermissionsChanged(uids, callback); + if (!result) { + HILOG_ERROR("RegisterAllPermissionsChanged call error"); + return false; + } + + PermissionsKey permissonsKey{.callback = callbackRef, .uids = uids}; + + std::lock_guard lock(permissionsCallbackMutex); + auto ret = permissionsCallback.emplace(permissonsKey, callback); + if (!ret.second) { + HILOG_ERROR("InnerRegisterPermissionsChanged emplace failed"); + return false; + } + HILOG_INFO("InnerRegisterPermissionsChanged end"); + return true; +} + +napi_value RegisterAllPermissionsChanged(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + napi_value thisArg; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + HILOG_INFO("ARGCSIZE is = %{public}zu.", argc); + std::string permissionEvent; + ParseString(env, permissionEvent, argv[0]); + if (permissionEvent == PERMISSION_CHANGE && argc == ARGS_SIZE_THREE) { + std::vector uids; + ParseInt32Array(env, uids, argv[ARGS_SIZE_ONE]); + AsyncRegisterPermissions *asyncCallbackInfo = + new AsyncRegisterPermissions{.env = env, .asyncWork = nullptr, .uids = uids}; + HILOG_INFO("RegisterAllPermissionsChanged permissionChange asyncCallback."); + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); + + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_RegisterPermissionsChanged", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncRegisterPermissions *asyncCallbackInfo = (AsyncRegisterPermissions *)data; + InnerRegisterPermissionsChanged(env, asyncCallbackInfo->uids, asyncCallbackInfo->callback); + }, + [](napi_env env, napi_status status, void *data) { + AsyncRegisterPermissions *asyncCallbackInfo = (AsyncRegisterPermissions *)data; + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { + AsyncRegisterAllPermissions *asyncCallbackInfo = + new AsyncRegisterAllPermissions{.env = env, .asyncWork = nullptr}; + HILOG_INFO("RegisterAllPermissionsChanged anyPermissionChange asyncCallback."); + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], 1, &asyncCallbackInfo->callback)); + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_RegisterAllPermissionsChanged", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncRegisterAllPermissions *asyncCallbackInfo = (AsyncRegisterAllPermissions *)data; + InnerRegisterAllPermissionsChanged(env, asyncCallbackInfo->callback); + }, + [](napi_env env, napi_status status, void *data) { + AsyncRegisterAllPermissions *asyncCallbackInfo = (AsyncRegisterAllPermissions *)data; + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 0, &result)); + return result; +} + +static bool InnerUnregisterAnyPermissionsChanged(napi_env env, napi_ref callbackRef) +{ + HILOG_INFO("InnerUnregisterAnyPermissionsChanged"); + std::lock_guard lock(anyPermissionsCallbackMutex); + for (const auto &item : anyPermissionsCallback) { + napi_value callback = 0; + napi_value ref = 0; + napi_get_reference_value(env, item.first, &callback); + napi_get_reference_value(env, callbackRef, &ref); + bool result = false; + auto napiRet = napi_strict_equals(env, callback, ref, &result); + HILOG_INFO("status is = %{public}d.", napiRet); + if (result) { + HILOG_INFO("find value in anyPermissionsCallback"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + HILOG_ERROR("can not get iBundleMgr"); + return false; + } + auto result = iBundleMgr->UnregisterPermissionsChanged(item.second); + if (!result) { + HILOG_ERROR("UnregisterPermissionsChanged call error"); + return false; + } + anyPermissionsCallback.erase(item.first); + return true; + } + } + HILOG_INFO("InnerUnregisterAnyPermissionsChanged end"); + return false; +} + +static bool InnerUnregisterPermissionsChanged(napi_env env, const std::vector &uids, napi_ref callbackRef) +{ + HILOG_INFO("InnerUnregisterPermissionsChanged"); + std::lock_guard lock(permissionsCallbackMutex); + for (const auto &item : permissionsCallback) { + napi_value callback = 0; + napi_value ref = 0; + napi_get_reference_value(env, item.first.callback, &callback); + napi_get_reference_value(env, callbackRef, &ref); + bool result = false; + auto napiRet = napi_strict_equals(env, callback, ref, &result); + HILOG_INFO("status is = %{public}d.", napiRet); + if (result && uids == item.first.uids) { + HILOG_INFO("find value in permissionsCallback"); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + HILOG_ERROR("can not get iBundleMgr"); + return false; + } + auto result = iBundleMgr->UnregisterPermissionsChanged(item.second); + if (!result) { + HILOG_ERROR("InnerUnregisterPermissionsChanged call error"); + return false; + } + HILOG_INFO("call UnregisterPermissionsChanged success = %{public}d", permissionsCallback.size()); + permissionsCallback.erase(item.first); + return true; + } + HILOG_INFO("can not find value in permissionsCallback"); + } + HILOG_INFO("InnerUnregisterPermissionsChanged end"); + return false; +} + +napi_value UnregisterPermissionsChanged(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + napi_value thisArg; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); + std::string permissionEvent; + ParseString(env, permissionEvent, argv[0]); + + if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { + AsyncUnregisterPermissions *asyncCallbackInfo = new AsyncUnregisterPermissions{ + .env = env, + .asyncWork = nullptr, + }; + HILOG_INFO("UnregisterAnyPermissionsChanged asyncCallback."); + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], 1, &asyncCallbackInfo->callback)); + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_UnreegisterAnyPermissionsChanged", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncUnregisterPermissions *asyncCallbackInfo = (AsyncUnregisterPermissions *)data; + asyncCallbackInfo->ret = InnerUnregisterAnyPermissionsChanged(env, asyncCallbackInfo->callback); + }, + [](napi_env env, napi_status status, void *data) { + AsyncUnregisterPermissions *asyncCallbackInfo = (AsyncUnregisterPermissions *)data; + napi_value result[ARGS_SIZE_ONE] = {0}; + napi_value callback = 0; + napi_value undefined = 0; + napi_value callResult = 0; + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->ret ? CODE_SUCCESS : CODE_FAILED); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_call_function(env, undefined, callback, ARGS_SIZE_ONE, &result[PARAM0], &callResult); + if (asyncCallbackInfo->callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else if (permissionEvent == PERMISSION_CHANGE && argc == ARGS_SIZE_THREE) { + std::vector uids; + ParseInt32Array(env, uids, argv[ARGS_SIZE_ONE]); + AsyncUnregisterPermissions *asyncCallbackInfo = + new AsyncUnregisterPermissions{.env = env, .asyncWork = nullptr, .uids = uids}; + HILOG_INFO("UnregisterPermissionsChanged asyncCallback."); + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); + napi_value resourceName; + napi_create_string_latin1(env, "NAPI_UnreegisterPermissionsChanged", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncUnregisterPermissions *asyncCallbackInfo = (AsyncUnregisterPermissions *)data; + asyncCallbackInfo->ret = + InnerUnregisterPermissionsChanged(env, asyncCallbackInfo->uids, asyncCallbackInfo->callback); + }, + [](napi_env env, napi_status status, void *data) { + AsyncUnregisterPermissions *asyncCallbackInfo = (AsyncUnregisterPermissions *)data; + napi_value result[ARGS_SIZE_ONE] = {0}; + napi_value callback = 0; + napi_value undefined = 0; + napi_value callResult = 0; + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->ret ? CODE_SUCCESS : CODE_FAILED); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_call_function(env, undefined, callback, ARGS_SIZE_ONE, &result[PARAM0], &callResult); + if (asyncCallbackInfo->callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 0, &result)); + return result; +} + +static int InnerCheckPermission(napi_env env, const std::string &bundleName, const std::string &permission) +{ + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + HILOG_ERROR("can not get iBundleMgr"); + return false; + }; + int ret = iBundleMgr->CheckPermission(bundleName, permission); + + return ret; +} + +/** + * Promise and async callback + */ +napi_value CheckPermission(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = {0}; + napi_value thisArg = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + std::string bundleName; + ParseString(env, bundleName, argv[0]); + std::string permission; + ParseString(env, permission, argv[1]); + + AsyncPermissionCallbackInfo *asyncCallbackInfo = new AsyncPermissionCallbackInfo{ + .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .permission = permission}; + if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { + HILOG_INFO("CheckPermission asyncCallback."); + napi_value resourceName; + napi_create_string_latin1(env, "CheckPermission", NAPI_AUTO_LENGTH, &resourceName); + + napi_valuetype valuetype = napi_undefined; + napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], 1, &asyncCallbackInfo->callback)); + + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; + asyncCallbackInfo->ret = + InnerCheckPermission(env, asyncCallbackInfo->bundleName, asyncCallbackInfo->permission); + }, + [](napi_env env, napi_status status, void *data) { + AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; + napi_value result[ARGS_SIZE_TWO] = {0}; + napi_value callback = 0; + napi_value undefined = 0; + napi_value callResult = 0; + napi_get_undefined(env, &undefined); + napi_create_int32(env, asyncCallbackInfo->ret, &result[PARAM1]); + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->ret == 0 ? CODE_SUCCESS : CODE_FAILED); + napi_get_reference_value(env, asyncCallbackInfo->callback, &callback); + napi_call_function(env, undefined, callback, ARGS_SIZE_TWO, &result[PARAM0], &callResult); + + if (asyncCallbackInfo->callback != nullptr) { + napi_delete_reference(env, asyncCallbackInfo->callback); + } + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } + napi_value result; + NAPI_CALL(env, napi_create_int32(env, 1, &result)); + return result; + } else { + HILOG_INFO("BundleMgr::CheckPermission promise."); + napi_deferred deferred; + napi_value promise; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncCallbackInfo->deferred = deferred; + + napi_value resourceName; + napi_create_string_latin1(env, "CheckPermission", NAPI_AUTO_LENGTH, &resourceName); + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; + asyncCallbackInfo->ret = + InnerCheckPermission(env, asyncCallbackInfo->bundleName, asyncCallbackInfo->permission); + }, + [](napi_env env, napi_status status, void *data) { + HILOG_INFO("=================load================="); + AsyncPermissionCallbackInfo *asyncCallbackInfo = (AsyncPermissionCallbackInfo *)data; + napi_value result; + napi_create_int32(asyncCallbackInfo->env, asyncCallbackInfo->ret, &result); + napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); + napi_delete_async_work(env, asyncCallbackInfo->asyncWork); + delete asyncCallbackInfo; + }, + (void *)asyncCallbackInfo, + &asyncCallbackInfo->asyncWork); + napi_queue_async_work(env, asyncCallbackInfo->asyncWork); + + napi_value ret = nullptr; + NAPI_CALL(env, napi_get_null(env, &ret)); + if (ret == nullptr) { + if (asyncCallbackInfo != nullptr) { + delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; + } + } return promise; } } @@ -2734,10 +3697,10 @@ void CreateAbilityTypeObject(napi_env env, napi_value value) void CreateAbilitySubTypeObject(napi_env env, napi_value value) { napi_value nUnspecified; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nUnspecified)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nUnspecified)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "UNSPECIFIED", nUnspecified)); napi_value nCa; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nCa)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &nCa)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "CA", nCa)); } @@ -2776,15 +3739,15 @@ void CreateLaunchModeObject(napi_env env, napi_value value) void CreateModuleUpdateFlagObject(napi_env env, napi_value value) { napi_value nFlagModuleUpgradeCheck; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nFlagModuleUpgradeCheck)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nFlagModuleUpgradeCheck)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "FLAG_MODULE_UPGRADE_CHECK", nFlagModuleUpgradeCheck)); napi_value nFlagModuleUpgradeInstall; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nFlagModuleUpgradeInstall)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &nFlagModuleUpgradeInstall)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "FLAG_MODULE_UPGRADE_INSTALL", nFlagModuleUpgradeInstall)); napi_value nFlagModuleUpgradeinstallWithConfigWindows; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &nFlagModuleUpgradeinstallWithConfigWindows)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 2, &nFlagModuleUpgradeinstallWithConfigWindows)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property( env, value, "FLAG_MODULE_UPGRADE_INSTALL_WITH_CONFIG_WINDOWS", nFlagModuleUpgradeinstallWithConfigWindows)); @@ -2793,51 +3756,51 @@ void CreateModuleUpdateFlagObject(napi_env env, napi_value value) void CreateFormTypeObject(napi_env env, napi_value value) { napi_value nJava; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nJava)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nJava)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "JAVA", nJava)); napi_value nJs; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nJs)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &nJs)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "JS", nJs)); } void CreateColorModeObject(napi_env env, napi_value value) { napi_value nAutoMode; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_FAILED, &nAutoMode)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, -1, &nAutoMode)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "AUTO_MODE", nAutoMode)); napi_value nDarkMode; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nDarkMode)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nDarkMode)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "DARK_MODE", nDarkMode)); napi_value nLightMode; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nLightMode)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &nLightMode)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "LIGHT_MODE", nLightMode)); } void CreateGrantStatusObject(napi_env env, napi_value value) { napi_value nPermissionDenied; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_FAILED, &nPermissionDenied)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, -1, &nPermissionDenied)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "PERMISSION_DENIED", nPermissionDenied)); napi_value nPermissionGranted; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nPermissionGranted)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nPermissionGranted)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "PERMISSION_GRANTED", nPermissionGranted)); } void CreateModuleRemoveFlagObject(napi_env env, napi_value value) { napi_value nFlagModuleNotUsedByForm; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nFlagModuleNotUsedByForm)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nFlagModuleNotUsedByForm)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "FLAG_MODULE_NOT_USED_BY_FORM", nFlagModuleNotUsedByForm)); napi_value nFlagModuleUsedByForm; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nFlagModuleUsedByForm)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &nFlagModuleUsedByForm)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "FLAG_MODULE_USED_BY_FORM", nFlagModuleUsedByForm)); napi_value nFlagModuleNotUsedByShortcut; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &nFlagModuleNotUsedByShortcut)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 2, &nFlagModuleNotUsedByShortcut)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "FLAG_MODULE_NOT_USED_BY_SHORTCUT", nFlagModuleNotUsedByShortcut)); napi_value nFlagModuleUsedByShortcut; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_THREE, &nFlagModuleUsedByShortcut)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 3, &nFlagModuleUsedByShortcut)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "FLAG_MODULE_USED_BY_SHORTCUT", nFlagModuleUsedByShortcut)); } @@ -2845,13 +3808,13 @@ void CreateModuleRemoveFlagObject(napi_env env, napi_value value) void CreateSignatureCompareResultObject(napi_env env, napi_value value) { napi_value nSignatureMatched; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nSignatureMatched)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nSignatureMatched)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "SIGNATURE_MATCHED", nSignatureMatched)); napi_value nSignatureNotMatched; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nSignatureNotMatched)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &nSignatureNotMatched)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "SIGNATURE_NOT_MATCHED", nSignatureNotMatched)); napi_value nSignatureUnknownBundle; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &nSignatureUnknownBundle)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 2, &nSignatureUnknownBundle)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "SIGNATURE_UNKNOWN_BUNDLE", nSignatureUnknownBundle)); } @@ -2859,15 +3822,15 @@ void CreateSignatureCompareResultObject(napi_env env, napi_value value) void CreateShortcutExistenceObject(napi_env env, napi_value value) { napi_value nShortcutExistenceExists; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nShortcutExistenceExists)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nShortcutExistenceExists)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "SHORTCUT_EXISTENCE_EXISTS", nShortcutExistenceExists)); napi_value nShortcutExistenceNotExists; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nShortcutExistenceNotExists)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 1, &nShortcutExistenceNotExists)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "SHORTCUT_EXISTENCE_NOT_EXISTS", nShortcutExistenceNotExists)); napi_value nShortcutExistenceUnknow; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &nShortcutExistenceUnknow)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 2, &nShortcutExistenceUnknow)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "SHORTCUT_EXISTENCE_UNKNOW", nShortcutExistenceUnknow)); } @@ -2875,7 +3838,7 @@ void CreateShortcutExistenceObject(napi_env env, napi_value value) void CreateQueryShortCutFlagObject(napi_env env, napi_value value) { napi_value nQueryShortCutHome; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nQueryShortCutHome)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nQueryShortCutHome)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "QUERY_SHORTCUT_HOME", nQueryShortCutHome)); } diff --git a/kits/appkit/napi/bundlemgr/bundle_mgr.h b/kits/appkit/napi/bundlemgr/bundle_mgr.h index e3625bcd718135ede73b30e45d0c1a41abbad067..e3a80b53da39818e8a26057196d6704fa8b89ce7 100644 --- a/kits/appkit/napi/bundlemgr/bundle_mgr.h +++ b/kits/appkit/napi/bundlemgr/bundle_mgr.h @@ -73,6 +73,16 @@ struct AsyncPermissionDefCallbackInfo { bool ret = false; }; +struct AsyncPermissionCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback = 0; + std::string bundleName; + std::string permission; + int ret = -1; +}; + struct AsyncBundleInfosCallbackInfo { napi_env env; napi_async_work asyncWork; @@ -157,6 +167,37 @@ struct AsyncShortcutInfosCallbackInfo { bool ret = false; }; +struct AsyncModuleUsageRecordsCallbackInfo { + napi_env env; + napi_async_work asyncWork; + napi_deferred deferred; + napi_ref callback = 0; + int32_t number; + std::vector moduleUsageRecords; + bool ret = false; +}; + +struct AsyncRegisterAllPermissions { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; +}; + +struct AsyncRegisterPermissions { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + std::vector uids; +}; + +struct AsyncUnregisterPermissions { + napi_env env; + napi_async_work asyncWork; + napi_ref callback = 0; + std::vector uids; + bool ret = false; +}; + extern napi_value g_classBundleInstaller; napi_value GetApplicationInfos(napi_env env, napi_callback_info); @@ -174,6 +215,10 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info); napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info); napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info); napi_value GetShortcutInfos(napi_env env, napi_callback_info info); +napi_value GetModuleUsageRecords(napi_env env, napi_callback_info info); +napi_value RegisterAllPermissionsChanged(napi_env env, napi_callback_info info); +napi_value UnregisterPermissionsChanged(napi_env env, napi_callback_info info); +napi_value CheckPermission(napi_env env, napi_callback_info info); void CreateAbilityTypeObject(napi_env env, napi_value value); void CreateAbilitySubTypeObject(napi_env env, napi_value value); void CreateDisplayOrientationObject(napi_env env, napi_value value); diff --git a/kits/appkit/napi/bundlemgr/native_module.cpp b/kits/appkit/napi/bundlemgr/native_module.cpp index 47abb8f2e7acd1abfbc58b30578f398dd8bd0793..0fbea0b8bfc86b5617319ab52c03d50ef622f763 100644 --- a/kits/appkit/napi/bundlemgr/native_module.cpp +++ b/kits/appkit/napi/bundlemgr/native_module.cpp @@ -94,6 +94,10 @@ static napi_value Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getFormsInfo", GetFormsInfoByApp), DECLARE_NAPI_FUNCTION("getAllFormsInfo", GetAllFormsInfo), DECLARE_NAPI_FUNCTION("getShortcutInfos", GetShortcutInfos), + DECLARE_NAPI_FUNCTION("getModuleUsageRecords", GetModuleUsageRecords), + DECLARE_NAPI_FUNCTION("on", RegisterAllPermissionsChanged), + DECLARE_NAPI_FUNCTION("off", UnregisterPermissionsChanged), + DECLARE_NAPI_FUNCTION("checkPermission", CheckPermission), DECLARE_NAPI_PROPERTY("AbilityType", nAbilityType), DECLARE_NAPI_PROPERTY("AbilitySubType", nAbilitySubType), DECLARE_NAPI_PROPERTY("DisplayOrientation", nDisplayOrientation), diff --git a/kits/appkit/napi/bundlemgr/permission_callback.cpp b/kits/appkit/napi/bundlemgr/permission_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4aa91d5d32b27d9b974bf25c96caead4bd48e56 --- /dev/null +++ b/kits/appkit/napi/bundlemgr/permission_callback.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 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 "permission_callback.h" +#include "hilog_wrapper.h" + +PermissionCallback::PermissionCallback(napi_env env, napi_ref callback) : env_(env), callback_(callback) +{} + +PermissionCallback::~PermissionCallback() +{ + if (callback_ != nullptr) { + napi_delete_reference(env_, callback_); + } +} + +void PermissionCallback::OnChanged(const int32_t uid) +{ + uv_loop_s *loop = nullptr; +#if NAPI_VERSION >= 2 + napi_get_uv_event_loop(env_, &loop); +#endif // NAPI_VERSION >= 2 + + uv_work_t *work = new uv_work_t; + CallbackInfo *callbackInfo = new (std::nothrow) CallbackInfo{ + .env = env_, + .callback = callback_, + .uid = uid, + }; + + work->data = (void *)callbackInfo; + + uv_queue_work( + loop, + work, + [](uv_work_t *work) {}, + [](uv_work_t *work, int status) { + HILOG_INFO("CallOnPermissonChanged, uv_queue_work"); + // JS Thread + CallbackInfo *event = (CallbackInfo *)work->data; + napi_value result[2] = {0}; + + napi_value callResult = nullptr; + napi_value eCode = nullptr; + NAPI_CALL_RETURN_VOID(event->env, napi_create_int32(event->env, 0, &eCode)); + napi_create_object(event->env, &callResult); + napi_set_named_property(event->env, callResult, "code", eCode); + result[0] = callResult; + // create uid + NAPI_CALL_RETURN_VOID(event->env, napi_create_int32(event->env, event->uid, &result[1])); + + napi_value callback = 0; + napi_value undefined = 0; + napi_get_undefined(event->env, &undefined); + napi_value callbackResult = 0; + napi_get_reference_value(event->env, event->callback, &callback); + napi_call_function(event->env, undefined, callback, 2, &result[0], &callbackResult); + delete event; + delete work; + }); + + HILOG_INFO("OnChanged, end"); +} \ No newline at end of file diff --git a/kits/appkit/napi/bundlemgr/permission_callback.h b/kits/appkit/napi/bundlemgr/permission_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..bcda69feb68e7da884d1afa0adddfb0c8e8b0bc0 --- /dev/null +++ b/kits/appkit/napi/bundlemgr/permission_callback.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 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 PERMISSION_CALLBACK_H +#define PERMISSION_CALLBACK_H + +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +#include "nocopyable.h" +#include "on_permission_changed_callback_host.h" + +struct CallbackInfo { + napi_env env; + napi_ref callback = 0; + int32_t uid; +}; + +class PermissionCallback : public OHOS::AppExecFwk::OnPermissionChangedCallbackHost { +public: + PermissionCallback(napi_env env, napi_ref callback); + virtual ~PermissionCallback(); + virtual void OnChanged(const int32_t uid) override; + + +private: + napi_env env_; + napi_ref callback_; + DISALLOW_COPY_AND_MOVE(PermissionCallback); +}; + +#endif // PERMISSION_CALLBACK_H \ No newline at end of file diff --git a/kits/appkit/native/app/include/ability_start_setting.h b/kits/appkit/native/app/include/ability_start_setting.h deleted file mode 100644 index f6b466636b095df296663ee68c895762647d1f2c..0000000000000000000000000000000000000000 --- a/kits/appkit/native/app/include/ability_start_setting.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2021 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 ABILITY_START_SETTING_H -#define ABILITY_START_SETTING_H - -#include -#include -#include -#include -#include "parcel.h" - -namespace OHOS { -namespace AppExecFwk { - -class AbilityStartSetting final : public Parcelable, public std::enable_shared_from_this { -public: - static const std::string BOUNDS_KEY; - static const std::string WINDOW_DISPLAY_ID_KEY; - static const std::string WINDOW_MODE_KEY; - - /** - * @brief Construct copy function. - * @param other indicates instance of abilitystartsetting object - * @return none. - */ - AbilityStartSetting(const AbilityStartSetting &other); - /** - * @brief Overload assignment operation. - * @param other indicates instance of abilitystartsetting object. - * @return Returns current instance of abilitystartsetting object. - */ - AbilityStartSetting &operator=(const AbilityStartSetting &other); - - virtual ~AbilityStartSetting() = default; - - /** - * @brief Obtains the names of all the attributes that have been added to this AbilityStartSetting object. - * - * @return Returns the set of attribute names included in this AbilityStartSetting object. - */ - std::set GetPropertiesKey(); - - /** - * @brief Obtains the names of all the attributes that have been added to this AbilityStartSetting object. - * - * @return Returns the set of attribute names included in this AbilityStartSetting object. - */ - static std::shared_ptr GetEmptySetting(); - - /** - * @brief Checks whether this AbilityStartSetting object is empty. - * - * @return Returns true if this AbilityStartSetting object is empty and animatorOption is null; returns false - * otherwise. - */ - bool IsEmpty(); - /** - * @brief Sets the names of all the attributes of the AbilityStartSetting object. - * - * @param key Indicates the name of the key. - * @param value The window display mode of the values. - */ - void AddProperty(const std::string &key, const std::string &value); - - /** - * @brief Gets the name of the attributes of the AbilityStartSetting object. - * - * @param key Indicates the name of the key. - * @return Returns value Indicates the value of the attributes of the AbilityStartSetting object - */ - std::string GetProperty(const std::string &key); - - /* - * @brief Write the data of AbilityStartSetting to the file stream - * @param parcel indicates write the data of AbilityStartSetting to the file stream through parcel - * @return bool - */ - bool Marshalling(Parcel &parcel) const; - - /** - * @brief Reading file stream through parcel to generate AbilityStartSetting instance - * @param parcel indicates reading file stream through parcel to generate AbilityStartSetting instance - * @return AbilityStartSetting shared_ptr - */ - static AbilityStartSetting *Unmarshalling(Parcel &parcel); - -protected: - AbilityStartSetting() = default; - friend std::shared_ptr AbilityStartSettingCreator(); - -private: - std::map abilityStarKey_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // ABILITY_START_SETTING_H diff --git a/kits/appkit/native/app/include/context.h b/kits/appkit/native/app/include/context.h index f08b28c2ecc45b3a55f1bb4e24b5506fe21d56b0..4c1726936b1024ef35bea769ad238176ba6bdc46 100755 --- a/kits/appkit/native/app/include/context.h +++ b/kits/appkit/native/app/include/context.h @@ -23,7 +23,6 @@ #include "ability_info.h" #include "process_info.h" #include "resource_manager.h" -#include "ability_start_setting.h" #include "dummy_hap_module_info.h" #include "hap_module_info.h" #include "task/task_priority.h" @@ -33,7 +32,7 @@ namespace OHOS { namespace AppExecFwk { using Want = OHOS::AAFwk::Want; - +using AbilityStartSetting = AAFwk::AbilityStartSetting; // Request permissions for user #define OHOS_REQUEST_PERMISSION_BUNDLENAME "com.ohos.systemui" #define OHOS_REQUEST_PERMISSION_ABILITY_NAME "com.ohos.systemui.systemdialog.MainAbility" diff --git a/kits/appkit/native/app/src/ability_start_setting.cpp b/kits/appkit/native/app/src/ability_start_setting.cpp deleted file mode 100644 index 9961e3378547ab81ae9121904f6316130d9f8c00..0000000000000000000000000000000000000000 --- a/kits/appkit/native/app/src/ability_start_setting.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2021 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 "ability_start_setting.h" -#include -#include "app_log_wrapper.h" -#include "string_ex.h" - -using namespace OHOS; - -namespace OHOS { -namespace AppExecFwk { - -const std::string AbilityStartSetting::BOUNDS_KEY = "bounds"; -const std::string AbilityStartSetting::WINDOW_DISPLAY_ID_KEY = "windowId"; -const std::string AbilityStartSetting::WINDOW_MODE_KEY = "windowMode"; - -/** - * @brief Construct copy function. - * @param other indicates instance of abilitystartsetting object - * @return none. - */ -AbilityStartSetting::AbilityStartSetting(const AbilityStartSetting &other) -{ - abilityStarKey_.clear(); - abilityStarKey_ = other.abilityStarKey_; -} -/** - * @brief Overload assignment operation. - * @param other indicates instance of abilitystartsetting object. - * @return Returns current instance of abilitystartsetting object. - */ -AbilityStartSetting &AbilityStartSetting::operator=(const AbilityStartSetting &other) -{ - if (this != &other) { - abilityStarKey_.clear(); - abilityStarKey_ = other.abilityStarKey_; - } - return *this; -} -/** - * @brief Inner function to create AbilityStartSetting - * - * @return Returns the shared_ptr of AbilityStartSetting object. - */ -std::shared_ptr AbilityStartSettingCreator() -{ - std::shared_ptr abilityStartSetting{new (std::nothrow) AbilityStartSetting()}; - return abilityStartSetting; -} - -/** - * @brief Obtains an empty AbilityStartSetting object. - * - * @return Returns the btains an empty AbilityStartSetting object. - */ -std::shared_ptr AbilityStartSetting::GetEmptySetting() -{ - return AbilityStartSettingCreator(); -} - -/** - * @brief Obtains the names of all the attributes that have been added to this AbilityStartSetting object. - * - * @return Returns the set of attribute names included in this AbilityStartSetting object. - */ -std::set AbilityStartSetting::GetPropertiesKey() -{ - std::set abilityStartSet; - abilityStartSet.clear(); - - for (auto it : abilityStarKey_) { - abilityStartSet.emplace(it.first); - } - return abilityStartSet; -} - -/** - * @brief Checks whether this AbilityStartSetting object is empty. - * - * @return Returns true if this AbilityStartSetting object is empty and animatorOption is null; returns false otherwise. - */ -bool AbilityStartSetting::IsEmpty() -{ - return (abilityStarKey_.size() == 0); -} - -/** - * @brief Sets the names of all the attributes of the AbilityStartSetting object. - * - * @param key Indicates the name of the key. - * @param value The window display mode of the values. - */ -void AbilityStartSetting::AddProperty(const std::string &key, const std::string &value) -{ - abilityStarKey_[key] = value; -} - -/** - * @brief Gets the name of the attributes of the AbilityStartSetting object. - * - * @param key Indicates the name of the key. - * @return Returns value Indicates the value of the attributes of the AbilityStartSetting object - */ -std::string AbilityStartSetting::GetProperty(const std::string &key) -{ - auto it = abilityStarKey_.find(key); - if (it == abilityStarKey_.end()) { - return std::string(); - } - return abilityStarKey_[key]; -} - -/** - * @brief Write the data of AbilityStartSetting to the file stream - * @param parcel indicates write the data of AbilityStartSetting to the file stream through parcel - * @return bool - */ -bool AbilityStartSetting::Marshalling(Parcel &parcel) const -{ - size_t size = abilityStarKey_.size(); - - // 1. Number of key value pairs written - parcel.WriteUint32((uint32_t)size); - - std::map::const_iterator it; - - // 2. Write the key and value strings - for (auto pair : abilityStarKey_) { - // 1.key - parcel.WriteString16(Str8ToStr16(pair.first)); - // 2.data content - parcel.WriteString16(Str8ToStr16(pair.second)); - } - - return true; -} - -/** - * @brief Reading file stream through parcel to generate AbilityStartSetting instance - * @param parcel indicates reading file stream through parcel to generate AbilityStartSetting instance - * @return AbilityStartSetting shared_ptr - */ -AbilityStartSetting *AbilityStartSetting::Unmarshalling(Parcel &parcel) -{ - AbilityStartSetting *abilityStartSetting = new (std::nothrow) AbilityStartSetting(); - if (abilityStartSetting == nullptr) { - return nullptr; - } - // 1. Number of key value pairs read - uint32_t size = 0; - parcel.ReadUint32(size); - std::u16string keyReadString16; - std::u16string dataReadString16; - for (size_t i = 0; (i < size) && abilityStartSetting; i++) { - // 1.key - keyReadString16 = parcel.ReadString16(); - // 2.data content - dataReadString16 = parcel.ReadString16(); - abilityStartSetting->abilityStarKey_[Str16ToStr8(keyReadString16)] = Str16ToStr8(dataReadString16); - keyReadString16.clear(); - dataReadString16.clear(); - } - - return abilityStartSetting; -} - -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/kits/appkit/native/app/src/application_context.cpp b/kits/appkit/native/app/src/application_context.cpp index bc7797af428e23c0e9ae5de907c3687ec0b1fa39..5ae36a1525d715738b7152b784f5406ca6f90d98 100755 --- a/kits/appkit/native/app/src/application_context.cpp +++ b/kits/appkit/native/app/src/application_context.cpp @@ -199,12 +199,15 @@ int ApplicationContext::GetMissionId() std::shared_ptr ApplicationContext::CreateParallelTaskDispatcher( const std::string &name, const TaskPriority &priority) { + APP_LOGI("ApplicationContext::CreateParallelTaskDispatcher begin"); if (taskDispatcherContext_ == nullptr) { APP_LOGE("ApplicationContext::CreateParallelTaskDispatcher taskDispatcherContext_ is nullptr"); return nullptr; } - return taskDispatcherContext_->CreateParallelDispatcher(name, priority); + std::shared_ptr task = taskDispatcherContext_->CreateParallelDispatcher(name, priority); + APP_LOGI("ApplicationContext::CreateParallelTaskDispatcher end"); + return task; } /** @@ -218,12 +221,15 @@ std::shared_ptr ApplicationContext::CreateParallelTaskDispatcher std::shared_ptr ApplicationContext::CreateSerialTaskDispatcher( const std::string &name, const TaskPriority &priority) { + APP_LOGI("ApplicationContext::CreateSerialTaskDispatcher begin"); if (taskDispatcherContext_ == nullptr) { APP_LOGE("ApplicationContext::CreateSerialTaskDispatcher taskDispatcherContext_ is nullptr"); return nullptr; } - return taskDispatcherContext_->CreateSerialDispatcher(name, priority); + std::shared_ptr task = taskDispatcherContext_->CreateSerialDispatcher(name, priority); + APP_LOGI("ApplicationContext::CreateSerialTaskDispatcher end"); + return task; } /** @@ -235,12 +241,15 @@ std::shared_ptr ApplicationContext::CreateSerialTaskDispatcher( */ std::shared_ptr ApplicationContext::GetGlobalTaskDispatcher(const TaskPriority &priority) { + APP_LOGI("ApplicationContext::GetGlobalTaskDispatcher begin"); if (taskDispatcherContext_ == nullptr) { APP_LOGE("ApplicationContext::GetGlobalTaskDispatcher taskDispatcherContext_ is nullptr"); return nullptr; } - return taskDispatcherContext_->GetGlobalTaskDispatcher(priority); + std::shared_ptr task = taskDispatcherContext_->GetGlobalTaskDispatcher(priority); + APP_LOGI("ApplicationContext::GetGlobalTaskDispatcher end"); + return task; } } // namespace AppExecFwk diff --git a/kits/appkit/native/app/src/context_deal.cpp b/kits/appkit/native/app/src/context_deal.cpp index b84ff9650b75f5fb7a3d844e30cba22581e8a5d5..12830529e858e5187f51d198c08c2e5d303d1a96 100755 --- a/kits/appkit/native/app/src/context_deal.cpp +++ b/kits/appkit/native/app/src/context_deal.cpp @@ -53,10 +53,12 @@ std::shared_ptr ContextDeal::GetProcessInfo() const */ void ContextDeal::SetProcessInfo(const std::shared_ptr &info) { + APP_LOGI("ContextDeal::SetProcessInfo begin"); if (info == nullptr) { APP_LOGE("ContextDeal::SetProcessInfo failed, info is empty"); return; } + APP_LOGI("ContextDeal::SetProcessInfo end"); processInfo_ = info; } @@ -78,11 +80,13 @@ std::shared_ptr ContextDeal::GetApplicationInfo() const */ void ContextDeal::SetApplicationInfo(const std::shared_ptr &info) { + APP_LOGI("ContextDeal::SetApplicationInfo begin"); if (info == nullptr) { APP_LOGE("ContextDeal::SetApplicationInfo failed, info is empty"); return; } applicationInfo_ = info; + APP_LOGI("ContextDeal::SetApplicationInfo end"); } /** @@ -102,11 +106,13 @@ std::shared_ptr ContextDeal::GetApplicationContext() const */ void ContextDeal::SetApplicationContext(const std::shared_ptr &context) { + APP_LOGI("ContextDeal::SetApplicationContext begin"); if (context == nullptr) { APP_LOGE("ContextDeal::SetApplicationContext failed, context is empty"); return; } appContext_ = context; + APP_LOGI("ContextDeal::SetApplicationContext end"); } /** @@ -148,11 +154,13 @@ const std::shared_ptr ContextDeal::GetAbilityInfo() */ void ContextDeal::SetAbilityInfo(const std::shared_ptr &info) { + APP_LOGI("ContextDeal::SetAbilityInfo begin"); if (info == nullptr) { APP_LOGE("ContextDeal::SetAbilityInfo failed, info is empty"); return; } abilityInfo_ = info; + APP_LOGI("ContextDeal::SetAbilityInfo end"); } /** @@ -172,11 +180,13 @@ std::shared_ptr ContextDeal::GetContext() */ void ContextDeal::SetContext(const std::shared_ptr &context) { + APP_LOGI("ContextDeal::SetContext begin"); if (context == nullptr) { APP_LOGE("ContextDeal::SetContext failed, context is empty"); return; } abilityContext_ = context; + APP_LOGI("ContextDeal::SetContext end"); } /** @@ -187,15 +197,18 @@ void ContextDeal::SetContext(const std::shared_ptr &context) */ sptr ContextDeal::GetBundleManager() const { + APP_LOGI("ContextDeal::GetBundleManager begin"); auto bundleObj = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); if (bundleObj == nullptr) { APP_LOGE("failed to get bundle manager service"); return nullptr; } - - APP_LOGI("get bundle manager proxy success."); - return iface_cast(bundleObj); + APP_LOGI("ContextDeal::GetBundleManager before iface_cast"); + sptr bms = iface_cast(bundleObj); + APP_LOGI("ContextDeal::GetBundleManager after iface_cast"); + APP_LOGI("ContextDeal::GetBundleManager end"); + return bms; } /** @@ -215,11 +228,13 @@ std::shared_ptr ContextDeal::GetResourceManag */ void ContextDeal::SetProfile(const std::shared_ptr &profile) { + APP_LOGI("ContextDeal::SetProfile begin"); if (profile == nullptr) { APP_LOGE("ContextDeal::SetProfile failed, profile is nullptr"); return; } profile_ = profile; + APP_LOGI("ContextDeal::SetProfile end"); } /** @@ -241,8 +256,11 @@ std::shared_ptr ContextDeal::GetProfile() const */ bool ContextDeal::DeleteFile(const std::string &fileName) { + APP_LOGI("ContextDeal::DeleteFile begin"); std::string path = GetDataDir() + CONTEXT_DEAL_FILE_SEPARATOR + fileName; - return OHOS::RemoveFile(path); + bool ret = OHOS::RemoveFile(path); + APP_LOGI("ContextDeal::DeleteFile end"); + return ret; } /** @@ -320,6 +338,7 @@ std::string ContextDeal::GetDataDir() */ std::string ContextDeal::GetDir(const std::string &name, int mode) { + APP_LOGI("ContextDeal::GetDir begin"); if (applicationInfo_ == nullptr) { APP_LOGE("ContextDeal::GetDir failed, applicationInfo_ == nullptr"); return ""; @@ -330,6 +349,7 @@ std::string ContextDeal::GetDir(const std::string &name, int mode) OHOS::ForceCreateDirectory(dir); OHOS::ChangeModeDirectory(dir, mode); } + APP_LOGI("ContextDeal::GetDir end"); return dir; } @@ -380,12 +400,14 @@ std::string ContextDeal::GetFilesDir() */ std::string ContextDeal::GetNoBackupFilesDir() { + APP_LOGI("ContextDeal::GetNoBackupFilesDir begin"); std::string dir = applicationInfo_->dataDir + CONTEXT_DEAL_NO_BACKUP_Files; if (!OHOS::FileExists(dir)) { APP_LOGI("ContextDeal::GetDir GetNoBackupFilesDir is not exits"); OHOS::ForceCreateDirectory(dir); OHOS::ChangeModeDirectory(dir, MODE); } + APP_LOGI("ContextDeal::GetNoBackupFilesDir end"); return dir; } @@ -476,14 +498,17 @@ void ContextDeal::UnauthUriPermission(const std::string &permission, const Uri & */ sptr ContextDeal::GetAbilityManager() { + APP_LOGI("ContextDeal::GetAbilityManager begin"); auto remoteObject = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); if (remoteObject == nullptr) { APP_LOGE("failed to get ability manager service"); return nullptr; } - - APP_LOGI("get bundle ability proxy success."); - return iface_cast(remoteObject); + APP_LOGI("ContextDeal::SetPattern before iface_cast"); + sptr ams = iface_cast(remoteObject); + APP_LOGI("ContextDeal::SetPattern after iface_cast"); + APP_LOGI("ContextDeal::GetAbilityManager end"); + return ams; } /** @@ -496,13 +521,15 @@ sptr ContextDeal::GetAbilityManager() */ std::string ContextDeal::GetAppType() { + APP_LOGI("ContextDeal::GetAppType begin"); sptr ptr = GetBundleManager(); if (ptr == nullptr) { APP_LOGE("GetAppType failed to get bundle manager service"); return ""; } - - return ptr->GetAppType(applicationInfo_->bundleName); + std::string retString = ptr->GetAppType(applicationInfo_->bundleName); + APP_LOGI("ContextDeal::GetAppType end"); + return retString; } /** @@ -577,18 +604,21 @@ std::string ContextDeal::GetDistributedDir() */ void ContextDeal::SetPattern(int patternId) { + APP_LOGI("ContextDeal::SetPattern begin"); if (resourceManager_ != nullptr) { if (!pattern_.empty()) { pattern_.clear(); } - + APP_LOGI("ContextDeal::SetPattern before resourceManager_->GetPatternById"); OHOS::Global::Resource::RState errval = resourceManager_->GetPatternById(patternId, pattern_); + APP_LOGI("ContextDeal::SetPattern after resourceManager_->GetPatternById"); if (errval != OHOS::Global::Resource::RState::SUCCESS) { APP_LOGE("ContextDeal::SetPattern GetPatternById(patternId:%d) retval is %u", patternId, errval); } } else { APP_LOGE("ContextDeal::SetPattern resourceManager_ is nullptr"); } + APP_LOGI("ContextDeal::SetPattern end"); } /** @@ -738,19 +768,23 @@ void ContextDeal::SerUriString(const std::string &uri) */ std::string ContextDeal::GetString(int resId) { + APP_LOGI("ContextDeal::GetString begin"); if (resourceManager_ == nullptr) { APP_LOGE("ContextDeal::GetString resourceManager_ is nullptr"); return ""; } std::string ret; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetStringById"); OHOS::Global::Resource::RState errval = resourceManager_->GetStringById(resId, ret); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetStringById"); if (errval == OHOS::Global::Resource::RState::SUCCESS) { return ret; } else { APP_LOGE("ContextDeal::GetString GetStringById(resId:%d) retval is %u", resId, errval); return ""; } + APP_LOGI("ContextDeal::GetString end"); } /** @@ -762,19 +796,23 @@ std::string ContextDeal::GetString(int resId) */ std::vector ContextDeal::GetStringArray(int resId) { + APP_LOGI("ContextDeal::GetStringArray begin"); if (resourceManager_ == nullptr) { APP_LOGE("ContextDeal::GetStringArray resourceManager_ is nullptr"); return std::vector(); } std::vector retv; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetStringArrayById"); OHOS::Global::Resource::RState errval = resourceManager_->GetStringArrayById(resId, retv); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetStringArrayById"); if (errval == OHOS::Global::Resource::RState::SUCCESS) { return retv; } else { APP_LOGE("ContextDeal::GetStringArray GetStringArrayById(resId:%d) retval is %u", resId, errval); return std::vector(); } + APP_LOGI("ContextDeal::GetStringArray end"); } /** @@ -786,19 +824,23 @@ std::vector ContextDeal::GetStringArray(int resId) */ std::vector ContextDeal::GetIntArray(int resId) { + APP_LOGI("ContextDeal::GetIntArray begin"); if (resourceManager_ == nullptr) { APP_LOGE("ContextDeal::GetIntArray resourceManager_ is nullptr"); return std::vector(); } std::vector retv; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetIntArrayById"); OHOS::Global::Resource::RState errval = resourceManager_->GetIntArrayById(resId, retv); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetIntArrayById"); if (errval == OHOS::Global::Resource::RState::SUCCESS) { return retv; } else { APP_LOGE("ContextDeal::GetIntArray GetIntArrayById(resId:%d) retval is %u", resId, errval); return std::vector(); } + APP_LOGI("ContextDeal::GetIntArray end"); } /** @@ -808,10 +850,11 @@ std::vector ContextDeal::GetIntArray(int resId) */ std::map ContextDeal::GetTheme() { + APP_LOGI("ContextDeal::GetTheme begin"); if (theme_.empty()) { SetTheme(GetThemeId()); } - + APP_LOGI("ContextDeal::GetTheme end"); return theme_; } @@ -822,6 +865,7 @@ std::map ContextDeal::GetTheme() */ void ContextDeal::SetTheme(int themeId) { + APP_LOGI("ContextDeal::SetTheme begin"); if (resourceManager_ == nullptr) { APP_LOGE("ContextDeal::SetTheme resourceManager_ is nullptr"); return; @@ -836,15 +880,16 @@ void ContextDeal::SetTheme(int themeId) if (!theme_.empty()) { theme_.clear(); } - + APP_LOGI("ContextDeal::GetString before resourceManager_->GetThemeById"); OHOS::Global::Resource::RState errval = resourceManager_->GetThemeById(themeId, theme_); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetThemeById"); if (errval != OHOS::Global::Resource::RState::SUCCESS) { APP_LOGE("ContextDeal::SetTheme GetThemeById(themeId:%d) retval is %u", themeId, errval); return; } // hapModInfo->themeId = themeId; - + APP_LOGI("ContextDeal::SetTheme end"); return; } @@ -855,7 +900,9 @@ void ContextDeal::SetTheme(int themeId) */ std::map ContextDeal::GetPattern() { + APP_LOGI("ContextDeal::GetPattern begin"); if (!pattern_.empty()) { + APP_LOGI("ContextDeal::GetPattern end"); return pattern_; } else { APP_LOGE("ContextDeal::GetPattern pattern_ is empty"); @@ -872,19 +919,23 @@ std::map ContextDeal::GetPattern() */ int ContextDeal::GetColor(int resId) { + APP_LOGI("ContextDeal::GetColor begin"); if (resourceManager_ == nullptr) { APP_LOGE("ContextDeal::GetColor resourceManager_ is nullptr"); return INVALID_RESOURCE_VALUE; } uint32_t ret = INVALID_RESOURCE_VALUE; + APP_LOGI("ContextDeal::GetString before resourceManager_->GetColorById"); OHOS::Global::Resource::RState errval = resourceManager_->GetColorById(resId, ret); + APP_LOGI("ContextDeal::GetString after resourceManager_->GetColorById"); if (errval == OHOS::Global::Resource::RState::SUCCESS) { return ret; } else { APP_LOGE("ContextDeal::GetColor GetColorById(resId:%d) retval is %u", resId, errval); return INVALID_RESOURCE_VALUE; } + APP_LOGI("ContextDeal::GetColor end"); } /** @@ -931,7 +982,9 @@ bool ContextDeal::TerminateAbilityResult(int startId) */ int ContextDeal::GetDisplayOrientation() { + APP_LOGI("ContextDeal::GetDisplayOrientation begin"); if (abilityInfo_ != nullptr) { + APP_LOGI("ContextDeal::GetDisplayOrientation end"); return static_cast(abilityInfo_->orientation); } else { APP_LOGE("ContextDeal::GetDisplayOrientation abilityInfo_ is nullptr"); @@ -947,6 +1000,7 @@ int ContextDeal::GetDisplayOrientation() */ std::string ContextDeal::GetPreferencesDir() { + APP_LOGI("ContextDeal::GetPreferencesDir begin"); if (!preferenceDir_.empty()) { return preferenceDir_; } @@ -992,7 +1046,7 @@ std::string ContextDeal::GetPreferencesDir() } preferenceDir_ = dataDir; - + APP_LOGI("ContextDeal::GetPreferencesDir end"); return preferenceDir_; } @@ -1003,6 +1057,7 @@ std::string ContextDeal::GetPreferencesDir() */ void ContextDeal::SetColorMode(int mode) { + APP_LOGI("ContextDeal::SetColorMode begin"); auto hapModInfo = GetHapModuleInfo(); if (hapModInfo == nullptr) { APP_LOGE("ContextDeal::SetColorMode hapModInfo is nullptr"); @@ -1016,6 +1071,7 @@ void ContextDeal::SetColorMode(int mode) } else { // default use AUTO hapModInfo->colorMode = ModuleColorMode::AUTO; } + APP_LOGI("ContextDeal::SetColorMode end"); } /** @@ -1025,12 +1081,13 @@ void ContextDeal::SetColorMode(int mode) */ int ContextDeal::GetColorMode() { + APP_LOGI("ContextDeal::GetColorMode begin"); auto hapModInfo = GetHapModuleInfo(); if (hapModInfo == nullptr) { APP_LOGE("ContextDeal::GetColorMode hapModInfo is nullptr"); return -1; } - + APP_LOGI("ContextDeal::GetColorMode end"); return static_cast(hapModInfo->colorMode); } @@ -1060,6 +1117,7 @@ int ContextDeal::GetMissionId() */ void ContextDeal::TerminateAndRemoveMission() { + APP_LOGI("ContextDeal::TerminateAndRemoveMission begin"); auto abilityManagerClient = AAFwk::AbilityManagerClient::GetInstance(); if (abilityManagerClient == nullptr) { APP_LOGE("ContextDeal::TerminateAndRemoveMission abilityManagerClient is nullptr"); @@ -1067,10 +1125,13 @@ void ContextDeal::TerminateAndRemoveMission() } std::vector removeIdList = {GetMissionId()}; + APP_LOGI("ContextDeal::TerminateAndRemoveMission before abilityManagerClient->RemoveMissions"); ErrCode errval = abilityManagerClient->RemoveMissions(removeIdList); + APP_LOGI("ContextDeal::TerminateAndRemoveMission after abilityManagerClient->RemoveMissions"); if (errval != ERR_OK) { APP_LOGW("ContextDeal::TerminateAndRemoveMission RemoveMissions retval is ERROR(%d)", errval); } + APP_LOGI("ContextDeal::TerminateAndRemoveMission end"); } /** @@ -1108,6 +1169,7 @@ std::shared_ptr ContextDeal::GetUITaskDispatcher() */ std::shared_ptr ContextDeal::GetMainTaskDispatcher() { + APP_LOGI("ContextDeal::GetMainTaskDispatcher begin"); if (mainTaskDispatcher_ != nullptr) { return mainTaskDispatcher_; } @@ -1125,7 +1187,7 @@ std::shared_ptr ContextDeal::GetMainTaskDispatcher() } mainTaskDispatcher_ = std::make_shared(config, mainEventRunner_); - + APP_LOGI("ContextDeal::GetMainTaskDispatcher end"); return mainTaskDispatcher_; } @@ -1140,12 +1202,15 @@ std::shared_ptr ContextDeal::GetMainTaskDispatcher() std::shared_ptr ContextDeal::CreateParallelTaskDispatcher( const std::string &name, const TaskPriority &priority) { + APP_LOGI("ContextDeal::CreateParallelTaskDispatcher begin"); if (appContext_ == nullptr) { APP_LOGE("ContextDeal::CreateParallelTaskDispatcher appContext_ is nullptr"); return nullptr; } - return appContext_->CreateParallelTaskDispatcher(name, priority); + std::shared_ptr task = appContext_->CreateParallelTaskDispatcher(name, priority); + APP_LOGI("ContextDeal::CreateParallelTaskDispatcher end"); + return task; } /** @@ -1159,12 +1224,15 @@ std::shared_ptr ContextDeal::CreateParallelTaskDispatcher( std::shared_ptr ContextDeal::CreateSerialTaskDispatcher( const std::string &name, const TaskPriority &priority) { + APP_LOGI("ContextDeal::CreateSerialTaskDispatcher begin"); if (appContext_ == nullptr) { APP_LOGE("ContextDeal::CreateSerialTaskDispatcher appContext_ is nullptr"); return nullptr; } - return appContext_->CreateSerialTaskDispatcher(name, priority); + std::shared_ptr task = appContext_->CreateSerialTaskDispatcher(name, priority); + APP_LOGI("ContextDeal::CreateSerialTaskDispatcher end"); + return task; } /** @@ -1176,12 +1244,15 @@ std::shared_ptr ContextDeal::CreateSerialTaskDispatcher( */ std::shared_ptr ContextDeal::GetGlobalTaskDispatcher(const TaskPriority &priority) { + APP_LOGI("ContextDeal::GetGlobalTaskDispatcher begin"); if (appContext_ == nullptr) { APP_LOGE("ContextDeal::GetGlobalTaskDispatcher appContext_ is nullptr"); return nullptr; } - return appContext_->GetGlobalTaskDispatcher(priority); + std::shared_ptr task = appContext_->GetGlobalTaskDispatcher(priority); + APP_LOGI("ContextDeal::GetGlobalTaskDispatcher end"); + return task; } /** @@ -1201,6 +1272,8 @@ void ContextDeal::SetRunner(const std::shared_ptr &runner) */ bool ContextDeal::HapModuleInfoRequestInit() { + APP_LOGI("ContextDeal::HapModuleInfoRequestInit begin"); + sptr ptr = GetBundleManager(); if (ptr == nullptr) { APP_LOGE("GetHapModuleInfo failed to get bundle manager service"); @@ -1213,11 +1286,13 @@ bool ContextDeal::HapModuleInfoRequestInit() } hapModuleInfoLocal_ = std::make_shared(); + APP_LOGI("ContextDeal::HapModuleInfoRequestInit before IBundleMgr->GetBundleManager"); if (!ptr->GetHapModuleInfo(*abilityInfo_.get(), *hapModuleInfoLocal_)) { APP_LOGE("IBundleMgr::GetHapModuleInfo failed, will retval false value"); return false; } - + APP_LOGI("ContextDeal::HapModuleInfoRequestInit after IBundleMgr->GetBundleManager"); + APP_LOGI("ContextDeal::HapModuleInfoRequestInit end"); return true; } diff --git a/kits/appkit/native/app/src/main_thread.cpp b/kits/appkit/native/app/src/main_thread.cpp index 2b66932ead34409bdeb8947cb9ff6d914e980f05..a2c94f9fd195023478e5db287946b03263277153 100644 --- a/kits/appkit/native/app/src/main_thread.cpp +++ b/kits/appkit/native/app/src/main_thread.cpp @@ -149,7 +149,7 @@ std::shared_ptr MainThread::GetApplicationImpl() */ bool MainThread::ConnectToAppMgr() { - APP_LOGI("MainThread::connectToAppMgr start"); + APP_LOGI("MainThread::ConnectToAppMgr start"); auto object = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); if (object == nullptr) { APP_LOGE("failed to get bundle manager service"); @@ -161,17 +161,21 @@ bool MainThread::ConnectToAppMgr() return false; } + APP_LOGI("%{public}s, Start calling AddDeathRecipient.", __func__); if (!object->AddDeathRecipient(deathRecipient_)) { APP_LOGE("failed to AddDeathRecipient"); return false; } + APP_LOGI("%{public}s, End calling AddDeathRecipient.", __func__); appMgr_ = iface_cast(object); if (appMgr_ == nullptr) { APP_LOGE("failed to iface_cast object to appMgr_"); return false; } + APP_LOGI("MainThread::connectToAppMgr before AttachApplication"); appMgr_->AttachApplication(this); + APP_LOGI("MainThread::connectToAppMgr after AttachApplication"); APP_LOGI("MainThread::connectToAppMgr end"); return true; } @@ -199,7 +203,7 @@ void MainThread::Attach() */ void MainThread::RemoveAppMgrDeathRecipient() { - APP_LOGD("MainThread::RemoveAppMgrDeathRecipient called"); + APP_LOGI("MainThread::RemoveAppMgrDeathRecipient called begin"); if (appMgr_ == nullptr) { APP_LOGE("MainThread::RemoveAppMgrDeathRecipient failed"); return; @@ -207,10 +211,13 @@ void MainThread::RemoveAppMgrDeathRecipient() sptr object = appMgr_->AsObject(); if (object != nullptr) { + APP_LOGI("%{public}s called. Start calling RemoveDeathRecipient.", __func__); object->RemoveDeathRecipient(deathRecipient_); + APP_LOGI("%{public}s called. End calling RemoveDeathRecipient.", __func__); } else { APP_LOGE("appMgr_->AsObject() failed"); } + APP_LOGI("%{public}s called end.", __func__); } /** @@ -231,11 +238,12 @@ std::shared_ptr MainThread::GetMainHandler() const */ void MainThread::ScheduleForegroundApplication() { - APP_LOGI("MainThread::scheduleForegroundApplication called"); + APP_LOGI("MainThread::scheduleForegroundApplication called begin"); auto task = [appThread = this]() { appThread->HandleForegroundApplication(); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("PostTask task failed"); } + APP_LOGI("MainThread::scheduleForegroundApplication called end."); } /** @@ -245,12 +253,13 @@ void MainThread::ScheduleForegroundApplication() */ void MainThread::ScheduleBackgroundApplication() { - APP_LOGI("MainThread::scheduleBackgroundApplication called"); + APP_LOGI("MainThread::scheduleBackgroundApplication called begin"); auto task = [appThread = this]() { appThread->HandleBackgroundApplication(); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleBackgroundApplication PostTask task failed"); } + APP_LOGI("MainThread::scheduleBackgroundApplication called end."); } /** @@ -260,12 +269,13 @@ void MainThread::ScheduleBackgroundApplication() */ void MainThread::ScheduleTerminateApplication() { - APP_LOGI("MainThread::scheduleTerminateApplication called"); + APP_LOGI("MainThread::scheduleTerminateApplication called begin"); auto task = [appThread = this]() { appThread->HandleTerminateApplication(); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleTerminateApplication PostTask task failed"); } + APP_LOGI("MainThread::scheduleTerminateApplication called."); } /** @@ -282,6 +292,7 @@ void MainThread::ScheduleShrinkMemory(const int level) if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleShrinkMemory PostTask task failed"); } + APP_LOGI("MainThread::scheduleShrinkMemory level: %{public}d end.", level); } /** @@ -291,12 +302,13 @@ void MainThread::ScheduleShrinkMemory(const int level) */ void MainThread::ScheduleProcessSecurityExit() { - APP_LOGI("MainThread::ScheduleProcessSecurityExit called"); + APP_LOGI("MainThread::ScheduleProcessSecurityExit called start"); auto task = [appThread = this]() { appThread->HandleProcessSecurityExit(); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleProcessSecurityExit PostTask task failed"); } + APP_LOGI("MainThread::ScheduleProcessSecurityExit called end"); } /** @@ -318,12 +330,13 @@ void MainThread::ScheduleLowMemory() */ void MainThread::ScheduleLaunchApplication(const AppLaunchData &data) { - APP_LOGI("MainThread::scheduleLaunchApplication called"); + APP_LOGI("MainThread::scheduleLaunchApplication start"); auto task = [appThread = this, data]() { appThread->HandleLaunchApplication(data); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleLaunchApplication PostTask task failed"); } + APP_LOGI("MainThread::scheduleLaunchApplication end."); } /** @@ -336,7 +349,7 @@ void MainThread::ScheduleLaunchApplication(const AppLaunchData &data) */ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) { - APP_LOGI("MainThread::scheduleLaunchAbility called"); + APP_LOGI("MainThread::scheduleLaunchAbility called start."); APP_LOGI( "MainThread::scheduleLaunchAbility AbilityInfo name:%{public}s type:%{public}d", info.name.c_str(), info.type); @@ -352,6 +365,7 @@ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptrPostTask(task)) { APP_LOGE("MainThread::ScheduleLaunchAbility PostTask task failed"); } + APP_LOGI("MainThread::scheduleLaunchAbility called end."); } /** @@ -363,11 +377,12 @@ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr &token) { - APP_LOGI("MainThread::scheduleCleanAbility called"); + APP_LOGI("MainThread::scheduleCleanAbility called start."); auto task = [appThread = this, token]() { appThread->HandleCleanAbility(token); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleCleanAbility PostTask task failed"); } + APP_LOGI("MainThread::scheduleCleanAbility called end."); } /** @@ -391,11 +406,12 @@ void MainThread::ScheduleProfileChanged(const Profile &profile) */ void MainThread::ScheduleConfigurationUpdated(const Configuration &config) { - APP_LOGI("MainThread::ScheduleConfigurationUpdated called"); + APP_LOGI("MainThread::ScheduleConfigurationUpdated called start."); auto task = [appThread = this, config]() { appThread->HandleConfigurationUpdated(config); }; if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::ScheduleConfigurationUpdated PostTask task failed"); } + APP_LOGI("MainThread::ScheduleConfigurationUpdated called end."); } /** @@ -408,6 +424,8 @@ void MainThread::ScheduleConfigurationUpdated(const Configuration &config) */ bool MainThread::CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) const { + APP_LOGI("MainThread::CheckLaunchApplicationParam called start."); + ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); ProcessInfo processInfo = appLaunchData.GetProcessInfo(); @@ -421,6 +439,7 @@ bool MainThread::CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) return false; } + APP_LOGI("MainThread::CheckLaunchApplicationParam called end."); return true; } @@ -434,6 +453,7 @@ bool MainThread::CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) */ bool MainThread::CheckAbilityItem(const std::shared_ptr &record) const { + APP_LOGI("MainThread::CheckAbilityItem called start."); if (record == nullptr) { APP_LOGE("MainThread::checkAbilityItem record is null"); return false; @@ -452,6 +472,7 @@ bool MainThread::CheckAbilityItem(const std::shared_ptr &rec return false; } + APP_LOGI("MainThread::CheckAbilityItem called end."); return true; } @@ -462,12 +483,14 @@ bool MainThread::CheckAbilityItem(const std::shared_ptr &rec */ void MainThread::HandleTerminateApplicationLocal() { - APP_LOGI("MainThread::HandleTerminateApplicationLocal called..."); + APP_LOGI("MainThread::HandleTerminateApplicationLocal called start."); if (application_ == nullptr) { APP_LOGE("MainThread::HandleTerminateApplicationLocal error!"); return; } + APP_LOGI("MainThread::HandleTerminateApplicationLocal before PerformTerminateStrong."); applicationImpl_->PerformTerminateStrong(); + APP_LOGI("MainThread::HandleTerminateApplicationLocal after PerformTerminateStrong."); std::shared_ptr runner = mainHandler_->GetEventRunner(); if (runner == nullptr) { APP_LOGE("MainThread::HandleTerminateApplicationLocal get manHandler error"); @@ -481,14 +504,19 @@ void MainThread::HandleTerminateApplicationLocal() SetRunnerStarted(false); #ifdef ABILITY_LIBRARY_LOADER + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. Start calling CloseAbilityLibrary."); CloseAbilityLibrary(); + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. End calling CloseAbilityLibrary."); #endif // ABILITY_LIBRARY_LOADER #ifdef APPLICATION_LIBRARY_LOADER if (handleAppLib_ != nullptr) { + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. Start calling dlclose."); dlclose(handleAppLib_); + APP_LOGI("MainThread::HandleTerminateApplicationLocal called. End calling dlclose."); handleAppLib_ = nullptr; } #endif // APPLICATION_LIBRARY_LOADER + APP_LOGI("MainThread::HandleTerminateApplicationLocal called end."); } /** @@ -498,7 +526,7 @@ void MainThread::HandleTerminateApplicationLocal() */ void MainThread::HandleProcessSecurityExit() { - APP_LOGI("MainThread::HandleProcessSecurityExit called"); + APP_LOGI("MainThread::HandleProcessSecurityExit called start."); if (abilityRecordMgr_ == nullptr) { APP_LOGE("MainThread::HandleProcessSecurityExit abilityRecordMgr_ is null"); return; @@ -511,6 +539,7 @@ void MainThread::HandleProcessSecurityExit() } HandleTerminateApplicationLocal(); + APP_LOGI("MainThread::HandleProcessSecurityExit called end."); } /** @@ -522,7 +551,7 @@ void MainThread::HandleProcessSecurityExit() */ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) { - APP_LOGI("MainThread::handleLaunchApplication called"); + APP_LOGI("MainThread::handleLaunchApplication called start."); if (application_ != nullptr) { APP_LOGE("MainThread::handleLaunchApplication already create application"); return; @@ -534,15 +563,19 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) } #ifdef ABILITY_LIBRARY_LOADER + APP_LOGI("MainThread::handleLaunchApplication Start calling LoadAbilityLibrary."); LoadAbilityLibrary(appLaunchData.GetApplicationInfo().moduleSourceDirs); + APP_LOGI("MainThread::handleLaunchApplication End calling LoadAbilityLibrary."); #endif // ABILITY_LIBRARY_LOADER #ifdef APPLICATION_LIBRARY_LOADER std::string appPath = applicationLibraryPath; + APP_LOGI("MainThread::handleLaunchApplication Start calling dlopen. appPath=%{public}s", appPath.c_str()); handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL); if (handleAppLib_ == nullptr) { APP_LOGE("Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror()); exit(-1); } + APP_LOGI("MainThread::handleLaunchApplication End calling dlopen."; #endif // APPLICATION_LIBRARY_LOADER ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); @@ -600,11 +633,13 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) return; } + APP_LOGI("MainThread::handleLaunchApplication. Start calling GetBundleManager."); sptr bundleMgr = contextDeal->GetBundleManager(); if (bundleMgr == nullptr) { APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr"); return; } + APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager."); BundleInfo bundleInfo; APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s", @@ -612,19 +647,23 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) appInfo.bundleName.c_str()); bundleMgr->GetBundleInfo(appInfo.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu", bundleInfo.moduleResPaths.size()); + APP_LOGI("MainThread::handleLaunchApplication moduleResPaths count: %{public}zu start", bundleInfo.moduleResPaths.size()); for (auto moduleResPath : bundleInfo.moduleResPaths) { if (!moduleResPath.empty()) { APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, moduleResPath: %{public}s", moduleResPath.length(), moduleResPath.c_str()); + APP_LOGI("MainThread::handleLaunchApplication. before resourceManager->AddResource."); if (!resourceManager->AddResource(moduleResPath.c_str())) { APP_LOGE("MainThread::handleLaunchApplication AddResource failed"); } + APP_LOGI("MainThread::handleLaunchApplication. after resourceManager->AddResource."); } } - + APP_LOGI("MainThread::handleLaunchApplication moduleResPaths end."); + APP_LOGI("MainThread::handleLaunchApplication before Resource::CreateResConfig."); std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + APP_LOGI("MainThread::handleLaunchApplication after Resource::CreateResConfig."); resConfig->SetLocaleInfo("zh", "Hans", "CN"); const icu::Locale *localeInfo = resConfig->GetLocaleInfo(); if (localeInfo != nullptr) { @@ -636,10 +675,21 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) APP_LOGI("MainThread::handleLaunchApplication localeInfo is nullptr."); } + APP_LOGI("MainThread::handleLaunchApplication. Start calling UpdateResConfig."); resourceManager->UpdateResConfig(*resConfig); + APP_LOGI("MainThread::handleLaunchApplication. End calling UpdateResConfig."); + + APP_LOGI("MainThread::handleLaunchApplication. Start calling initResourceManager."); contextDeal->initResourceManager(resourceManager); + APP_LOGI("MainThread::handleLaunchApplication. End calling initResourceManager."); + + APP_LOGI("MainThread::handleLaunchApplication. Start calling SetApplicationContext."); contextDeal->SetApplicationContext(application_); + APP_LOGI("MainThread::handleLaunchApplication. End calling SetApplicationContext."); + + APP_LOGI("MainThread::handleLaunchApplication. Start calling AttachBaseContext."); application_->AttachBaseContext(contextDeal); + APP_LOGI("MainThread::handleLaunchApplication. End calling AttachBaseContext."); abilityRecordMgr_ = std::make_shared(); if (abilityRecordMgr_ == nullptr) { @@ -647,22 +697,29 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) return; } + APP_LOGI("MainThread::handleLaunchApplication. Start calling SetAbilityRecordMgr."); application_->SetAbilityRecordMgr(abilityRecordMgr_); + APP_LOGI("MainThread::handleLaunchApplication. End calling SetAbilityRecordMgr."); applicationImpl_->SetRecordId(appLaunchData.GetRecordId()); applicationImpl_->SetApplication(application_); mainThreadState_ = MainThreadState::READY; + APP_LOGI("MainThread::handleLaunchApplication before PerformAppReady."); if (!applicationImpl_->PerformAppReady()) { APP_LOGE("HandleLaunchApplication::application applicationImpl_->PerformAppReady failed"); return; } - + APP_LOGI("MainThread::handleLaunchApplication after PerformAppReady."); // L1 needs to add corresponding interface ApplicationEnvImpl *pAppEvnIml = ApplicationEnvImpl::GetInstance(); if (pAppEvnIml) { pAppEvnIml->SetAppInfo(*applicationInfo_.get()); + } else { + APP_LOGE("HandleLaunchApplication::application pAppEvnIml is null"); } + + APP_LOGI("MainThread::handleLaunchApplication called end."); } /** @@ -674,26 +731,26 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) */ void MainThread::HandleLaunchAbility(const std::shared_ptr &abilityRecord) { - APP_LOGI("MainThread::handleLaunchAbility called"); + APP_LOGI("MainThread::handleLaunchAbility called start."); if (applicationImpl_ == nullptr) { - APP_LOGE("MainThread::ScheduleLaunchAbility applicationImpl_ is null"); + APP_LOGE("MainThread::HandleLaunchAbility applicationImpl_ is null"); return; } if (abilityRecordMgr_ == nullptr) { - APP_LOGE("MainThread::ScheduleLaunchAbility abilityRecordMgr_ is null"); + APP_LOGE("MainThread::HandleLaunchAbility abilityRecordMgr_ is null"); return; } if (abilityRecord == nullptr) { - APP_LOGE("MainThread::ScheduleLaunchAbility parameter(abilityRecord) is null"); + APP_LOGE("MainThread::HandleLaunchAbility parameter(abilityRecord) is null"); return; } auto abilityToken = abilityRecord->GetToken(); if (abilityToken == nullptr) { - APP_LOGE("MainThread::ScheduleLaunchAbility failed. abilityRecord->GetToken failed"); + APP_LOGE("MainThread::HandleLaunchAbility failed. abilityRecord->GetToken failed"); return; } @@ -712,10 +769,15 @@ void MainThread::HandleLaunchAbility(const std::shared_ptr & mainThreadState_ = MainThreadState::RUNNING; #ifdef APP_ABILITY_USE_TWO_RUNNER + APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain start."); AbilityThread::AbilityThreadMain(application_, abilityRecord); + APP_LOGI("MainThread::handleLaunchAbility. Start calling AbilityThreadMain end."); #else + APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain start."); AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner()); + APP_LOGI("MainThread::handleLaunchAbility. Start calling 2 AbilityThreadMain end."); #endif + APP_LOGI("MainThread::handleLaunchAbility called end."); } /** @@ -727,7 +789,7 @@ void MainThread::HandleLaunchAbility(const std::shared_ptr & */ void MainThread::HandleCleanAbilityLocal(const sptr &token) { - APP_LOGI("MainThread::HandleCleanAbilityLocal called"); + APP_LOGI("MainThread::HandleCleanAbilityLocal called start."); if (!IsApplicationReady()) { APP_LOGE("MainThread::HandleCleanAbilityLocal not init OHOSApplication, should launch application first"); return; @@ -765,6 +827,7 @@ void MainThread::HandleCleanAbilityLocal(const sptr &token) APP_LOGW("MainThread::HandleCleanAbilityLocal runner not found"); } #endif + APP_LOGI("MainThread::HandleCleanAbilityLocal called end."); } /** @@ -776,7 +839,7 @@ void MainThread::HandleCleanAbilityLocal(const sptr &token) */ void MainThread::HandleCleanAbility(const sptr &token) { - APP_LOGI("MainThread::handleCleanAbility called"); + APP_LOGI("MainThread::handleCleanAbility called start."); if (!IsApplicationReady()) { APP_LOGE("MainThread::handleCleanAbility not init OHOSApplication, should launch application first"); return; @@ -814,7 +877,10 @@ void MainThread::HandleCleanAbility(const sptr &token) APP_LOGW("MainThread::handleCleanAbility runner not found"); } #endif + APP_LOGI("MainThread::handleCleanAbility before AbilityCleaned."); appMgr_->AbilityCleaned(token); + APP_LOGI("MainThread::handleCleanAbility after AbilityCleaned."); + APP_LOGI("MainThread::handleCleanAbility called end."); } /** @@ -824,7 +890,7 @@ void MainThread::HandleCleanAbility(const sptr &token) */ void MainThread::HandleForegroundApplication() { - APP_LOGI("MainThread::handleForegroundApplication called..."); + APP_LOGI("MainThread::handleForegroundApplication called start."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { APP_LOGE("MainThread::handleForegroundApplication error!"); return; @@ -835,7 +901,10 @@ void MainThread::HandleForegroundApplication() return; } + APP_LOGI("MainThread::handleForegroundApplication before ApplicationForegrounded"); appMgr_->ApplicationForegrounded(applicationImpl_->GetRecordId()); + APP_LOGI("MainThread::handleForegroundApplication after ApplicationForegrounded"); + APP_LOGI("MainThread::handleForegroundApplication called end"); } /** @@ -845,7 +914,7 @@ void MainThread::HandleForegroundApplication() */ void MainThread::HandleBackgroundApplication() { - APP_LOGI("MainThread::handleBackgroundApplication called..."); + APP_LOGI("MainThread::handleBackgroundApplication called start."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { APP_LOGE("MainThread::handleBackgroundApplication error!"); @@ -856,8 +925,11 @@ void MainThread::HandleBackgroundApplication() APP_LOGE("MainThread::handleForegroundApplication error!, applicationImpl_->PerformBackground() failed"); return; } - + APP_LOGI("MainThread::handleBackgroundApplication before ApplicationBackgrounded"); appMgr_->ApplicationBackgrounded(applicationImpl_->GetRecordId()); + APP_LOGI("MainThread::handleBackgroundApplication after ApplicationBackgrounded"); + + APP_LOGI("MainThread::handleBackgroundApplication called end"); } /** @@ -867,31 +939,40 @@ void MainThread::HandleBackgroundApplication() */ void MainThread::HandleTerminateApplication() { - APP_LOGI("MainThread::handleTerminateApplication called..."); + APP_LOGI("MainThread::handleTerminateApplication called start."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { APP_LOGE("MainThread::handleTerminateApplication error!"); return; } + APP_LOGI("MainThread::handleTerminateApplication before PerformTerminate"); if (!applicationImpl_->PerformTerminate()) { APP_LOGE("MainThread::handleForegroundApplication error!, applicationImpl_->PerformTerminate() failed"); return; } + APP_LOGI("MainThread::handleTerminateApplication after PerformTerminate"); + APP_LOGI("MainThread::handleTerminateApplication before ApplicationTerminated"); appMgr_->ApplicationTerminated(applicationImpl_->GetRecordId()); + APP_LOGI("MainThread::handleTerminateApplication after ApplicationTerminated"); std::shared_ptr runner = mainHandler_->GetEventRunner(); if (runner == nullptr) { APP_LOGE("MainThread::handleTerminateApplication get manHandler error"); return; } + + APP_LOGI("MainThread::handleTerminateApplication before stop runner"); int ret = runner->Stop(); + APP_LOGI("MainThread::handleTerminateApplication after stop runner"); if (ret != ERR_OK) { APP_LOGE("MainThread::handleTerminateApplication failed. runner->Run failed ret = %{public}d", ret); } SetRunnerStarted(false); #ifdef ABILITY_LIBRARY_LOADER + APP_LOGI("MainThread::handleTerminateApplication. Start callint CloseAbilityLibrary."); CloseAbilityLibrary(); + APP_LOGI("MainThread::handleTerminateApplication. End callint CloseAbilityLibrary."); #endif // ABILITY_LIBRARY_LOADER #ifdef APPLICATION_LIBRARY_LOADER if (handleAppLib_ != nullptr) { @@ -899,6 +980,7 @@ void MainThread::HandleTerminateApplication() handleAppLib_ = nullptr; } #endif // APPLICATION_LIBRARY_LOADER + APP_LOGI("MainThread::handleTerminateApplication called end."); } /** @@ -910,7 +992,7 @@ void MainThread::HandleTerminateApplication() */ void MainThread::HandleShrinkMemory(const int level) { - APP_LOGI("MainThread::HandleShrinkMemory called..."); + APP_LOGI("MainThread::HandleShrinkMemory called start."); if (applicationImpl_ == nullptr) { APP_LOGE("MainThread::HandleShrinkMemory error! applicationImpl_ is null"); @@ -918,6 +1000,7 @@ void MainThread::HandleShrinkMemory(const int level) } applicationImpl_->PerformMemoryLevel(level); + APP_LOGI("MainThread::HandleShrinkMemory called end."); } /** @@ -929,7 +1012,7 @@ void MainThread::HandleShrinkMemory(const int level) */ void MainThread::HandleConfigurationUpdated(const Configuration &config) { - APP_LOGI("MainThread::HandleConfigurationUpdated called..."); + APP_LOGI("MainThread::HandleConfigurationUpdated called start."); if (applicationImpl_ == nullptr) { APP_LOGE("MainThread::HandleConfigurationUpdated error! applicationImpl_ is null"); @@ -937,10 +1020,12 @@ void MainThread::HandleConfigurationUpdated(const Configuration &config) } applicationImpl_->PerformConfigurationUpdated(config); + APP_LOGI("MainThread::HandleConfigurationUpdated called end."); } void MainThread::Init(const std::shared_ptr &runner) { + APP_LOGI("MainThread:Init Start"); mainHandler_ = std::make_shared(runner, this); auto task = [appThread = this]() { APP_LOGI("MainThread:MainHandler Start"); @@ -949,8 +1034,10 @@ void MainThread::Init(const std::shared_ptr &runner) if (!mainHandler_->PostTask(task)) { APP_LOGE("MainThread::Init PostTask task failed"); } - + APP_LOGI("MainThread:Init before CreateRunner."); TaskHandlerClient::GetInstance()->CreateRunner(); + APP_LOGI("MainThread:Init after CreateRunner."); + APP_LOGI("MainThread:Init end."); } void MainThread::Start() @@ -967,8 +1054,13 @@ void MainThread::Start() return; } + APP_LOGI("MainThread::main called start Init"); thread->Init(runner); + APP_LOGI("MainThread::main called end Init"); + + APP_LOGI("MainThread::main called start Attach"); thread->Attach(); + APP_LOGI("MainThread::main called end Attach"); int ret = runner->Run(); if (ret != ERR_OK) { @@ -976,7 +1068,7 @@ void MainThread::Start() } thread->RemoveAppMgrDeathRecipient(); - APP_LOGW("MainThread::main runner stopped"); + APP_LOGI("MainThread::main runner stopped"); } MainThread::MainHandler::MainHandler(const std::shared_ptr &runner, const sptr &thread) @@ -1002,10 +1094,13 @@ void MainThread::MainHandler::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::P */ bool MainThread::IsApplicationReady() const { + APP_LOGI("MainThread::IsApplicationReady called start"); if (application_ == nullptr || applicationImpl_ == nullptr) { + APP_LOGI("MainThread::IsApplicationReady called. application_=null or applicationImpl_=null"); return false; } + APP_LOGI("MainThread::IsApplicationReady called end"); return true; } @@ -1019,9 +1114,11 @@ bool MainThread::IsApplicationReady() const */ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths) { + APP_LOGI("MainThread::LoadAbilityLibrary called start"); #ifdef ACEABILITY_LIBRARY_LOADER std::string acelibdir("/system/lib/libace.z.so"); void *AceAbilityLib = nullptr; + APP_LOGI("MainThread::LoadAbilityLibrary. Start calling dlopen acelibdir."); AceAbilityLib = dlopen(acelibdir.c_str(), RTLD_NOW | RTLD_GLOBAL); if (AceAbilityLib == nullptr) { APP_LOGE("Fail to dlopen %{public}s, [%{public}s]", acelibdir.c_str(), dlerror()); @@ -1029,10 +1126,13 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths APP_LOGI("Success to dlopen %{public}s", acelibdir.c_str()); handleAbilityLib_.emplace_back(AceAbilityLib); } + APP_LOGI("MainThread::LoadAbilityLibrary. End calling dlopen."); #endif // ACEABILITY_LIBRARY_LOADER int size = libraryPaths.size(); + APP_LOGI("MainThread::LoadAbilityLibrary. size=%{public}d.", size); for (int index = 0; index < size; index++) { std::string libraryPath = libraryPaths[index]; + APP_LOGI("Try to scanDir %{public}s", libraryPath.c_str()); if (!ScanDir(libraryPath)) { APP_LOGE("Fail to scanDir %{public}s", libraryPath.c_str()); continue; @@ -1047,7 +1147,9 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths void *handleAbilityLib = nullptr; for (auto fileEntry : fileEntries_) { if (!fileEntry.empty()) { + APP_LOGI("MainThread::LoadAbilityLibrary. Start calling dlopen fileEntry."); handleAbilityLib = dlopen(fileEntry.c_str(), RTLD_NOW | RTLD_GLOBAL); + APP_LOGI("MainThread::LoadAbilityLibrary. End calling dlopen fileEntry."); if (handleAbilityLib == nullptr) { APP_LOGE("Fail to dlopen %{public}s, [%{public}s]", fileEntry.c_str(), dlerror()); exit(-1); @@ -1057,6 +1159,7 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths handleAbilityLib_.emplace_back(handleAbilityLib); } } + APP_LOGI("MainThread::LoadAbilityLibrary called end."); } /** @@ -1066,14 +1169,18 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths */ void MainThread::CloseAbilityLibrary() { + APP_LOGI("MainThread::CloseAbilityLibrary called start"); for (auto iter : handleAbilityLib_) { if (iter != nullptr) { + APP_LOGI("MainThread::CloseAbilityLibrary before dlclose"); dlclose(iter); + APP_LOGI("MainThread::CloseAbilityLibrary after dlclose"); iter = nullptr; } } handleAbilityLib_.clear(); fileEntries_.clear(); + APP_LOGI("MainThread::CloseAbilityLibrary called end"); } /** @@ -1085,15 +1192,19 @@ void MainThread::CloseAbilityLibrary() */ bool MainThread::ScanDir(const std::string &dirPath) { + APP_LOGI("MainThread::ScanDir called start. dirPath: %{public}s.", dirPath.c_str()); + APP_LOGI("MainThread::ScanDir before opendir."); DIR *dirp = opendir(dirPath.c_str()); if (dirp == nullptr) { APP_LOGE("MainThread::ScanDir open dir:%{private}s fail", dirPath.c_str()); return false; } - + APP_LOGI("MainThread::ScanDir after opendir."); struct dirent *df = nullptr; for (;;) { + APP_LOGI("MainThread::ScanDir before readdir."); df = readdir(dirp); + APP_LOGI("MainThread::ScanDir after readdir."); if (df == nullptr) { break; } @@ -1109,9 +1220,12 @@ bool MainThread::ScanDir(const std::string &dirPath) } } + APP_LOGI("MainThread::ScanDir before closedir."); if (closedir(dirp) == -1) { APP_LOGW("close dir fail"); } + APP_LOGI("MainThread::ScanDir after closedir."); + APP_LOGI("MainThread::ScanDir called end."); return true; } @@ -1127,7 +1241,10 @@ bool MainThread::ScanDir(const std::string &dirPath) */ bool MainThread::CheckFileType(const std::string &fileName, const std::string &extensionName) { - APP_LOGD("path is %{public}s, support suffix is %{public}s", fileName.c_str(), extensionName.c_str()); + APP_LOGD("MainThread::CheckFileType path is %{public}s, support suffix is %{public}s", + fileName.c_str(), + extensionName.c_str()); + if (fileName.empty()) { APP_LOGE("the file name is empty"); return false; @@ -1140,6 +1257,7 @@ bool MainThread::CheckFileType(const std::string &fileName, const std::string &e } std::string suffixStr = fileName.substr(position); + APP_LOGD("MainThread::CheckFileType end."); return LowerStr(suffixStr) == extensionName; } #endif // ABILITY_LIBRARY_LOADER diff --git a/kits/appkit/native/test/BUILD.gn b/kits/appkit/native/test/BUILD.gn index 653f2576e6a7de6b4f18d95edeee07d5931a8d09..2e163448994b8ee52eb192d636d02c8f417a0ffc 100755 --- a/kits/appkit/native/test/BUILD.gn +++ b/kits/appkit/native/test/BUILD.gn @@ -294,6 +294,7 @@ config("ability_start_setting_config") { "//foundation/appexecfwk/standard/kits/appkit/native/app/include", "//foundation/appexecfwk/common/log/include/", "//utils/native/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", ] } @@ -305,7 +306,10 @@ ohos_unittest("ability_start_setting_test") { ":ability_start_setting_config", ] - sources = [ "unittest/ability_start_setting_test.cpp" ] + sources = [ + "//foundation/aafwk/standard/services/abilitymgr/src/ability_start_setting.cpp", + "unittest/ability_start_setting_test.cpp", + ] deps = [ "//foundation/appexecfwk/standard/kits:appkit_native", diff --git a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h index c8869412690f0e7f846006f48c4aa4dfd6be5ea0..92a308e6c2738cdc06b29b1c656e99bafb3d7e1a 100644 --- a/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h +++ b/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -281,6 +281,23 @@ public: { return nullptr; }; + bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) + { + return true; + } + bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) + { + return true; + } + bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) + { + return true; + } + bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) + { + return true; + } }; class MockAbilityContextDeal : public ContextDeal { diff --git a/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp b/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp index 9f1cbeb88ffe45e554744de04a89a6eeded1843b..f06f27821287435a82dbaeb55d70045c40ab50bf 100644 --- a/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp +++ b/kits/appkit/native/test/mock/include/mock_resourceManager_interface1.cpp @@ -1,4 +1,17 @@ - +/* + * Copyright (c) 2021 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 "gmock/gmock.h" diff --git a/kits/appkit/native/test/unittest/ability_start_setting_test.cpp b/kits/appkit/native/test/unittest/ability_start_setting_test.cpp index 9661682ce84fc69e21ce6b6678a897106f06a8ea..1720b1739250b91ea2714f537e5982e65c45eebe 100755 --- a/kits/appkit/native/test/unittest/ability_start_setting_test.cpp +++ b/kits/appkit/native/test/unittest/ability_start_setting_test.cpp @@ -25,7 +25,7 @@ namespace AppExecFwk { using namespace testing::ext; using namespace OHOS; using namespace OHOS::AppExecFwk; - +using namespace OHOS::AAFwk; class AbilityStartSettingTest : public testing::Test { public: AbilityStartSettingTest() : abilityStartSetting_(nullptr) diff --git a/libs/test/moduletest/common/event_handler/event_handler_fd_listener_module_test.cpp b/libs/test/moduletest/common/event_handler/event_handler_fd_listener_module_test.cpp index f1e3e8e5cacc92c1439856f29c16fe485166f0f7..f062eabe239d4793467fe993350e73d93435b15a 100644 --- a/libs/test/moduletest/common/event_handler/event_handler_fd_listener_module_test.cpp +++ b/libs/test/moduletest/common/event_handler/event_handler_fd_listener_module_test.cpp @@ -139,7 +139,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, AddListener001, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(); auto myRunner = EventRunner::Create(false); @@ -191,7 +191,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, AddListener003, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(); auto myRunner = EventRunner::Create(true); @@ -216,7 +216,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, AddListener004, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto myRunner = EventRunner::Create(true); auto handler = std::make_shared(myRunner); @@ -239,7 +239,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, AddListener005, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(); auto handler = std::make_shared(nullptr); @@ -262,7 +262,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, RemoveListener001, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(); auto myRunner = EventRunner::Create(false); @@ -294,7 +294,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, RemoveListener002, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(); auto myRunner = EventRunner::Create(false); @@ -326,7 +326,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, TriggerShutdown001, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(); auto myRunner = EventRunner::Create(false); @@ -362,7 +362,7 @@ HWTEST_F(EventHandlerFdListenerModuleTest, TriggerException001, TestSize.Level1) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(fds[0]); auto myRunner = EventRunner::Create(false); diff --git a/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp b/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp index 0d035a301c3ebb36ea2c3a3b65f6d1780a0c221f..49dd92d3000cebb07331776f2d645edc82b5c7c4 100644 --- a/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp +++ b/libs/test/moduletest/common/event_handler/event_handler_press_module_test.cpp @@ -205,7 +205,7 @@ HWTEST_F(EventHandlerPressModuleTest, FdListenerPress001, TestSize.Level3) */ int32_t fds[] = {-1, -1}; int32_t pipe = pipe2(fds, O_NONBLOCK); - ASSERT_GE(pipe, 0); + EXPECT_GE(pipe, 0); auto listener = std::make_shared(); auto myRunner = EventRunner::Create(false); diff --git a/ohos.build b/ohos.build index fa4f3cb8c9a6bb3fd9faa74a7f41ddfbfe730273..a189b8a533a37cff44b2143b1a6f9c436f15feda 100644 --- a/ohos.build +++ b/ohos.build @@ -1,95 +1,115 @@ -{ - "parts": { - "appexecfwk_standard": { - "inner_kits": [ - { - "header": { - "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "header_files": [ - "ability_info.h", - "appexecfwk_errors.h", - "application_info.h", - "element_name.h", - "bundle_info.h" - ] - }, - "name": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base" - }, - { - "header": { - "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", - "header_files": [ - "appmgr/app_mgr_client.h", - "appmgr/iapp_state_callback.h", - "appmgr/app_state_callback_host.h", - "appmgr/app_mgr_constants.h", - "bundlemgr/bundle_installer_interface.h", - "bundlemgr/bundle_mgr_interface.h", - "bundlemgr/bundle_status_callback_interface.h", - "bundlemgr/clean_cache_callback_interface.h", - "bundlemgr/status_receiver_interface.h", - "appmgr/app_process_data.h" - ] - }, - "name": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core" - }, - { - "header": { - "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "header_files": [ - "event_handler_errors.h", - "event_handler.h", - "event_queue.h", - "event_runner.h", - "inner_event.h", - "file_descriptor_listener.h", - "native_implement_eventhandler.h" - ] - }, - "name": "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler" - }, - { - "header": { - "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/eventhandler_native/eventhandler", - "header_files": [ - "native_interface_eventhandler.h" - ] - }, - "name": "//foundation/appexecfwk/standard/interfaces/innerkits/eventhandler_native:eventhandler_native" - } - ], - "module_list": [ - "//foundation/appexecfwk/standard/common:common_target", - "//foundation/appexecfwk/standard/services:services_target", - "//foundation/appexecfwk/standard/tools:tools_target", - "//foundation/appexecfwk/standard/interfaces/innerkits:innerkits_target", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/appexecfwk/standard/kits:appexec", - "//foundation/appexecfwk/standard/sa_profile:appexecfwk_sa_profile", - "//foundation/appexecfwk/standard/sa_profile:foundation.rc", - "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc:ams_system_test_app", - "//foundation/appexecfwk/standard/kits/appkit/napi:napi_packages" - ], - "test_list": [ - "//foundation/appexecfwk/standard/kits/appkit/native/test:unittest", - "//foundation/appexecfwk/standard/kits/appkit/test:moduletest", - "//foundation/appexecfwk/standard/services/test:moduletest", - "//foundation/appexecfwk/standard/services/bundlemgr/test:unittest", - "//foundation/appexecfwk/standard/services/appmgr/test:unittest", - "//foundation/appexecfwk/standard/test/systemtest:systemtest", - "//foundation/appexecfwk/standard/tools/test:moduletest", - "//foundation/appexecfwk/standard/tools/test:unittest", - "//foundation/appexecfwk/standard/libs/libeventhandler/test:unittest", - "//foundation/appexecfwk/standard/libs/test:moduletest", - "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/test:unittest", - "//foundation/appexecfwk/standard/interfaces/innerkits/test:moduletest" - ], - - "variants": [ - "phone", - "ivi" - ] - } - }, - "subsystem": "appexecfwk" -} +{ + "aosp_java_api_allowlist": "//foundation/appexecfwk/adapter/appexecfwk-java-aosp-apis.txt", + "aosp_cxx_api_allowlist": "//foundation/appexecfwk/adapter/appexecfwk_cxx_api_allowlist.txt", + "parts": { + "appexecfwk_standard": { + "inner_kits": [ + { + "header": { + "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "header_files": [ + "ability_info.h", + "appexecfwk_errors.h", + "application_info.h", + "element_name.h", + "bundle_info.h", + "form_constants.h", + "form_js_info.h" + ] + }, + "name": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base" + }, + { + "header": { + "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "header_files": [ + "appmgr/app_mgr_client.h", + "appmgr/iapp_state_callback.h", + "appmgr/app_state_callback_host.h", + "appmgr/app_mgr_constants.h", + "bundlemgr/bundle_installer_interface.h", + "bundlemgr/bundle_mgr_interface.h", + "bundlemgr/bundle_status_callback_interface.h", + "bundlemgr/clean_cache_callback_interface.h", + "bundlemgr/status_receiver_interface.h", + "appmgr/app_process_data.h", + "formmgr/form_mgr_interface.h" + + ] + }, + "name": "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core" + }, + { + "header": { + "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "header_files": [ + "event_handler_errors.h", + "event_handler.h", + "event_queue.h", + "event_runner.h", + "inner_event.h", + "file_descriptor_listener.h", + "native_implement_eventhandler.h" + ] + }, + "name": "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler" + }, + { + "header": { + "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/eventhandler_native/eventhandler", + "header_files": [ + "native_interface_eventhandler.h" + ] + }, + "name": "//foundation/appexecfwk/standard/interfaces/innerkits/eventhandler_native:eventhandler_native" + }, + { + "header": { + "header_base": "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", + "header_files": [ + "form_callback_interface.h", + "form_host_client.h", + "form_mgr.h" + ] + }, + "name": "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit:fmskit_native" + } + ], + "module_list": [ + "//foundation/appexecfwk/standard/common:common_target", + "//foundation/appexecfwk/standard/services:services_target", + "//foundation/appexecfwk/standard/tools:tools_target", + "//foundation/appexecfwk/standard/interfaces/innerkits:innerkits_target", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/appexecfwk/standard/kits:appexec", + "//foundation/appexecfwk/standard/sa_profile:appexecfwk_sa_profile", + "//foundation/appexecfwk/standard/sa_profile:foundation.rc", + "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc:ams_system_test_app", + "//foundation/appexecfwk/standard/test/resource/bmssystemtestability/abilitySrc:bms_system_test_app", + "//foundation/appexecfwk/standard/kits/appkit/napi:napi_packages" + ], + "test_list": [ + "//foundation/appexecfwk/standard/kits/appkit/native/test:unittest", + "//foundation/appexecfwk/standard/kits/appkit/test:moduletest", + "//foundation/appexecfwk/standard/services/test:moduletest", + "//foundation/appexecfwk/standard/services/bundlemgr/test:unittest", + "//foundation/appexecfwk/standard/services/appmgr/test:unittest", + "//foundation/appexecfwk/standard/services/formmgr/test:unittest", + "//foundation/appexecfwk/standard/test/systemtest:systemtest", + "//foundation/appexecfwk/standard/tools/test:moduletest", + "//foundation/appexecfwk/standard/tools/test:systemtest", + "//foundation/appexecfwk/standard/tools/test:unittest", + "//foundation/appexecfwk/standard/libs/libeventhandler/test:unittest", + "//foundation/appexecfwk/standard/libs/test:moduletest", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/test:unittest", + "//foundation/appexecfwk/standard/interfaces/innerkits/test:moduletest" + ], + + "variants": [ + "phone", + "ivi" + ] + } + }, + "subsystem": "appexecfwk" +} diff --git a/sa_profile/403.xml b/sa_profile/403.xml new file mode 100644 index 0000000000000000000000000000000000000000..7176a66dd1c65c470f5b87e043ca7a7567495ef8 --- /dev/null +++ b/sa_profile/403.xml @@ -0,0 +1,27 @@ + + + + foundation + + 403 + /system/lib64/libfms.z.so + + + true + false + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn index 56173ba8a66946bda751c6d06753a2e5d0168119..180d06646bacb21d418edfbda746bf5abae1dc53 100644 --- a/sa_profile/BUILD.gn +++ b/sa_profile/BUILD.gn @@ -17,6 +17,7 @@ import("//build/ohos/sa_profile/sa_profile.gni") ohos_sa_profile("appexecfwk_sa_profile") { sources = [ "401.xml", + "403.xml", "501.xml", ] diff --git a/sa_profile/foundation.cfg b/sa_profile/foundation.cfg index 67a08206cc7cc134c6363a071e6200763f5a3227..bc7d4b9cfe60daa01f3f8b7c300587f37148a18e 100644 --- a/sa_profile/foundation.cfg +++ b/sa_profile/foundation.cfg @@ -2,22 +2,52 @@ "jobs" : [{ "name" : "init", "cmds" : [ + "mkdir /dev/memcg", + "mount cgroup none /dev/memcg memory", + "chown system system /dev/memcg", + "chown system system /dev/memcg/tasks", + "chown system system /dev/memcg/memory.oom_control", + "chown system system /dev/memcg/cgroup.event_control", + "chown system system /dev/memcg/memory.pressure_level", + "chmod 0755 /dev/memcg", + "chmod 0755 /dev/memcg/tasks", + "chmod 0755 /dev/memcg/memory.oom_control", + "chmod 0755 /dev/memcg/cgroup.event_control", + "chmod 0755 /dev/memcg/memory.pressure_level", + "mkdir /dev/cpuset", + "mount cgroup none /dev/cpuset cpuset", + "mkdir /dev/cpuset/background", + "chown system system /dev/cpuset", + "chown system system /dev/cpuset/tasks", + "chown system system /dev/cpuset/background", + "chown system system /dev/cpuset/background/tasks", + "chmod 0755 /dev/cpuset", + "chmod 0755 /dev/cpuset/tasks", + "chmod 0755 /dev/cpuset/background", + "chmod 0755 /dev/cpuset/background/tasks", + "write /dev/cpuset/background/cpuset.cpus 0", + "mkdir /dev/cpuctl", + "mount cgroup none /dev/cpuctl cpu", "mkdir /dev/cpuctl/background", + "chown system system /dev/cpuctl", + "chown system system /dev/cpuctl/tasks", "chown system system /dev/cpuctl/background", + "chown system system /dev/cpuctl/background/tasks", + "chmod 0755 /dev/cpuctl", + "chmod 0755 /dev/cpuctl/tasks", "chmod 0755 /dev/cpuctl/background", "chmod 0755 /dev/cpuctl/background/tasks", "write /dev/cpuctl/background/cpu.shares 512", - "write /dev/cpuset/background/cpus 0", "mkdir /dev/freezer", - "chown system system /dev/freezer", - "chmod 0755 /dev/freezer", "mount cgroup none /dev/freezer freezer", "mkdir /dev/freezer/frozen", "mkdir /dev/freezer/thawed", + "chown system system /dev/freezer", "chown system system /dev/freezer/frozen", "chown system system /dev/freezer/frozen/tasks", "chown system system /dev/freezer/thawed", "chown system system /dev/freezer/thawed/tasks", + "chmod 0755 /dev/freezer", "chmod 0755 /dev/freezer/frozen", "chmod 0755 /dev/freezer/frozen/tasks", "chmod 0755 /dev/freezer/thawed", diff --git a/sa_profile/foundation.rc b/sa_profile/foundation.rc index 805d83e87dfe60e597ff21f83b4914e035dd0676..69909f50ff1e87952d6dec01d9bba8bd07deb03b 100755 --- a/sa_profile/foundation.rc +++ b/sa_profile/foundation.rc @@ -15,9 +15,10 @@ on init # cpuctl subsystem # set background cpuctl mkdir /dev/cpuctl/background - chown system system /dev/cpuctl/background chmod 0755 /dev/cpuctl/background chmod 0755 /dev/cpuctl/background/tasks + chown system system /dev/cpuctl/background + chown system system /dev/cpuctl/background/tasks write /dev/cpuctl/background/cpu.shares 512 # cpuset subsystem diff --git a/services/BUILD.gn b/services/BUILD.gn index 03d564f6169a21e58b69d2fef4d1587cae3f20fa..ae099a3474808cfa85d87e3682163c5ab1f36b57 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -15,5 +15,6 @@ group("services_target") { deps = [ "appmgr:ams_target", "bundlemgr:bms_target", + "formmgr:fms_target", ] } diff --git a/services/appmgr/BUILD.gn b/services/appmgr/BUILD.gn index 2915693ea521132636107e36424cef2ef8d32185..116cb2e06395ff8fda307e96d9ce791223ba978e 100644 --- a/services/appmgr/BUILD.gn +++ b/services/appmgr/BUILD.gn @@ -62,7 +62,11 @@ ohos_executable("lmks") { } ohos_prebuilt_etc("lmks.rc") { - source = "lmks.rc" + if (use_musl) { + source = "lmks.cfg" + } else { + source = "lmks.rc" + } relative_install_dir = "init" subsystem_name = "appexecfwk" part_name = "appexecfwk_standard" diff --git a/services/appmgr/include/ability_running_record.h b/services/appmgr/include/ability_running_record.h index 5188c25211bf8ed8d337397ee2f69c97f6336ff6..630a806edfbbb3cb45f894aee3f48d4784cad209 100644 --- a/services/appmgr/include/ability_running_record.h +++ b/services/appmgr/include/ability_running_record.h @@ -154,7 +154,7 @@ private: int32_t visibility_ = 0; int32_t perceptibility_ = 0; int32_t connectionState_ = 0; - int64_t eventId_; + int64_t eventId_ = 0; AbilityState state_ = AbilityState::ABILITY_STATE_BEGIN; std::shared_ptr info_; sptr token_; diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 18d6d27549b65e9854328b4a9bda47e15e472368..d2694287daaf19e3afbcbc23056248b970250603 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -450,6 +450,14 @@ public: */ int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message); + /** + * SuspendApplication, Application state changed. + * + * @param appRecord, the app information. + * @param state, the app state. + */ + void OnAppStateChanged(const std::shared_ptr &appRecord, const ApplicationState state); + private: /** * StartAbility, load the ability that needed to be started(Start on the basis of the original process). @@ -513,14 +521,6 @@ private: std::shared_ptr GetAbilityRunningRecordByAbilityToken( const sptr &abilityToken) const; - /** - * SuspendApplication, Application state changed. - * - * @param appRecord, the app information. - * @param state, the app state. - */ - void OnAppStateChanged(const std::shared_ptr &appRecord, const ApplicationState state); - /** * StartProcess, load the ability that needed to be started(Start on a new boot process). * diff --git a/services/appmgr/include/app_running_manager.h b/services/appmgr/include/app_running_manager.h index 3f5c4a18f8d83dd0f39dd95865bacb88db13bed9..235ed77ab91c6842d62bb1f5b516e87efd15743d 100644 --- a/services/appmgr/include/app_running_manager.h +++ b/services/appmgr/include/app_running_manager.h @@ -126,6 +126,8 @@ public: void TerminateAbility(const sptr &token); bool GetPidsByBundleName(const std::string &bundleName, std::list &pids); + std::shared_ptr GetTerminatingAppRunningRecord(const sptr &abilityToken); + private: std::shared_ptr GetAbilityRunningRecord(const int64_t eventId); diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index bbc2cb3f7242a37ca117d416d35ab6eac3d4ab7e..a08cf5d9ad18c4e2435ceee04b59cf07e183b088 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -40,7 +40,7 @@ namespace AppExecFwk { class AbilityRunningRecord; class AppMgrServiceInner; -class AppRunningRecord { +class AppRunningRecord : public std::enable_shared_from_this { public: AppRunningRecord( const std::shared_ptr &info, const int32_t recordId, const std::string &processName); @@ -273,6 +273,8 @@ public: */ std::shared_ptr GetAbilityRunningRecordByToken(const sptr &token) const; + std::shared_ptr GetAbilityByTerminateLists(const sptr &token) const; + /** * UpdateAbilityState, update the ability status. * @@ -407,6 +409,7 @@ private: int64_t eventId_ = 0; // List of abilities running in the process std::map, std::shared_ptr> abilities_; + std::map, std::shared_ptr> terminateAbilitys_; std::list> foregroundingAbilityTokens_; std::weak_ptr appMgrServiceInner_; sptr appDeathRecipient_; diff --git a/services/appmgr/include/cgroup_manager.h b/services/appmgr/include/cgroup_manager.h index 71162d501cc97ccb6640e6c7d5bd6fecf270a85c..ea8d773c9c844c25915d2efaf30876176eee43f3 100644 --- a/services/appmgr/include/cgroup_manager.h +++ b/services/appmgr/include/cgroup_manager.h @@ -74,12 +74,12 @@ public: private: std::shared_ptr eventHandler_; - int cpusetTasksFds_[SCHED_POLICY_CPU_MAX]; - int cpuctlTasksFds_[SCHED_POLICY_CPU_MAX]; - int freezerTasksFds_[SCHED_POLICY_FREEZER_MAX]; - int memoryEventControlFd_; - int memoryEventFds_[LOW_MEMORY_LEVEL_MAX]; - int memoryPressureFds_[LOW_MEMORY_LEVEL_MAX]; + int cpusetTasksFds_[SCHED_POLICY_CPU_MAX] = {-1}; + int cpuctlTasksFds_[SCHED_POLICY_CPU_MAX] = {-1}; + int freezerTasksFds_[SCHED_POLICY_FREEZER_MAX] = {-1}; + int memoryEventControlFd_ = -1; + int memoryEventFds_[LOW_MEMORY_LEVEL_MAX] = {-1}; + int memoryPressureFds_[LOW_MEMORY_LEVEL_MAX] = {-1}; bool RegisterLowMemoryMonitor(const int memoryEventFds[LOW_MEMORY_LEVEL_MAX], const int memoryPressureFds[LOW_MEMORY_LEVEL_MAX], const int memoryEventControlFd, const LowMemoryLevel level, diff --git a/services/appmgr/include/process_optimizer.h b/services/appmgr/include/process_optimizer.h index 8e7b2f8a208df6ca937d44b3100f4fe49f17d3c0..18f446769e2bab26e0edf81bf2820f5984c3dfbd 100644 --- a/services/appmgr/include/process_optimizer.h +++ b/services/appmgr/include/process_optimizer.h @@ -40,7 +40,8 @@ public: using CgroupManagerPtr = std::shared_ptr; using LmksClientPtr = std::shared_ptr; - static constexpr int APP_SUSPEND_TIMEOUT_DEFAULT = 5000; // in milliseconds + static constexpr int APP_SUSPEND_TIMEOUT_DEFAULT = 5000; // in milliseconds + static constexpr int APP_SUSPEND_TIMEOUT_MAX = 30 * 1000; // in milliseconds public: ProcessOptimizer(const LmksClientPtr &lmksClient = nullptr, int suspendTimeout = APP_SUSPEND_TIMEOUT_DEFAULT); diff --git a/services/appmgr/lmks.cfg b/services/appmgr/lmks.cfg new file mode 100755 index 0000000000000000000000000000000000000000..e02a3865092b6c72b49216a8a0a5f4b22bc261e6 --- /dev/null +++ b/services/appmgr/lmks.cfg @@ -0,0 +1,17 @@ +{ + "jobs" : [{ + "name" : "late-fs", + "cmds" : [ + "start lmks" + ] + } + ], + "services" : [{ + "name" : "lmks", + "path" : ["/system/bin/lmks"], + "importance" : -20, + "uid" : "root", + "gid" : ["root"] + } + ] +} diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 29fb059ca382a945d878ea0c4fedfb2e10673c3b..4c4ffcd7361bb450c107dfd8d2bfa8f3fc5a1bd7 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -748,11 +748,13 @@ void AppMgrServiceInner::AbilityTerminated(const sptr &token) APP_LOGE("token is null!"); return; } - auto appRecord = GetAppRunningRecordByAbilityToken(token); + + auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token); if (!appRecord) { APP_LOGE("app is not exist!"); return; } + appRecord->AbilityTerminated(token); APP_LOGD("end"); } @@ -782,6 +784,7 @@ void AppMgrServiceInner::OnAppStateChanged( processData.processName = appRecord->GetProcessName(); processData.pid = appRecord->GetPriorityObject()->GetPid(); processData.appState = state; + processData.uid = appRecord->GetUid(); callback->OnAppStateChanged(processData); } } diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index c42cdbf13f8e2bf64f222810fe654bfe29ecf2c0..e2aa28e0b90e270c42da897b59de8cdefa03ce34 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -198,7 +198,7 @@ void AppRunningManager::HandleTerminateTimeOut(int64_t eventId) return; } auto abilityToken = abilityRecord->GetToken(); - auto appRecord = GetAppRunningRecordByAbilityToken(abilityToken); + auto appRecord = GetTerminatingAppRunningRecord(abilityToken); if (!appRecord) { APP_LOGE("%{public}s, appRecord is nullptr", __func__); return; @@ -207,6 +207,19 @@ void AppRunningManager::HandleTerminateTimeOut(int64_t eventId) APP_LOGI("%{public}s, end", __func__); } +std::shared_ptr AppRunningManager::GetTerminatingAppRunningRecord( + const sptr &abilityToken) +{ + std::lock_guard guard(lock_); + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord && appRecord->GetAbilityByTerminateLists(abilityToken)) { + return appRecord; + } + } + return nullptr; +} + std::shared_ptr AppRunningManager::GetAbilityRunningRecord(const int64_t eventId) { APP_LOGI("%{public}s, called", __func__); @@ -246,6 +259,10 @@ void AppRunningManager::HandleAbilityAttachTimeOut(const sptr &to return; } + if (appRecord->IsLastAbilityRecord(token)) { + appRecord->SetTerminating(); + } + appRecord->TerminateAbility(token, true); } void AppRunningManager::TerminateAbility(const sptr &token) diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index 1219d72cca1abb1f213d33a1c4fd7d58f0e19320..d6937a26423ee34ef7052c1edd5f9dcd84527688 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -125,7 +125,17 @@ std::shared_ptr AppRunningRecord::GetAbilityRunningRecord( const auto &iter = std::find_if(abilities_.begin(), abilities_.end(), [eventId](const auto &pair) { return pair.second->GetEventId() == eventId; }); - return ((iter == abilities_.end()) ? nullptr : iter->second); + if (iter != abilities_.end()) { + return iter->second; + } + + const auto &finder = std::find_if(terminateAbilitys_.begin(), + terminateAbilitys_.end(), + [eventId](const auto &pair) { return pair.second->GetEventId() == eventId; }); + if (finder != terminateAbilitys_.end()) { + return finder->second; + } + return nullptr; } void AppRunningRecord::ClearAbility(const std::shared_ptr &record) @@ -248,6 +258,20 @@ std::shared_ptr AppRunningRecord::GetAbilityRunningRecordB return nullptr; } +std::shared_ptr AppRunningRecord::GetAbilityByTerminateLists( + const sptr &token) const +{ + if (!token) { + APP_LOGE("token is null"); + return nullptr; + } + const auto &iter = terminateAbilitys_.find(token); + if (iter != terminateAbilitys_.end()) { + return iter->second; + } + return nullptr; +} + void AppRunningRecord::UpdateAbilityState(const sptr &token, const AbilityState state) { APP_LOGD("state is :%{public}d", static_cast(state)); @@ -293,6 +317,10 @@ void AppRunningRecord::AbilityForeground(const std::shared_ptrOnAppStateChanged(shared_from_this(), curState_); + } } else { APP_LOGW("wrong application state"); } @@ -359,6 +387,9 @@ void AppRunningRecord::TerminateAbility(const sptr &token, const return; } + terminateAbilitys_.emplace(token, abilityRecord); + abilities_.erase(token); + SendEvent( AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG, AMSEventHandler::TERMINATE_ABILITY_TIMEOUT, abilityRecord); @@ -389,15 +420,15 @@ void AppRunningRecord::AbilityTerminated(const sptr &token) APP_LOGE("eventHandler_ is nullptr"); return; } - - auto abilityRecord = GetAbilityRunningRecordByToken(token); + + auto abilityRecord = GetAbilityByTerminateLists(token); if (!abilityRecord) { APP_LOGE("AppRunningRecord::AbilityTerminated can not find ability record"); return; } - + eventHandler_->RemoveEvent(AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG, abilityRecord->GetEventId()); - abilities_.erase(token); + terminateAbilitys_.erase(token); if (abilities_.empty()) { ScheduleTerminate(); } diff --git a/services/appmgr/src/cgroup_manager.cpp b/services/appmgr/src/cgroup_manager.cpp index 56773b0af65ff3294ab11bbf0ed43262145f8567..bf563c26593c1bde25cf48bf4aaa04b31c41cfae 100644 --- a/services/appmgr/src/cgroup_manager.cpp +++ b/services/appmgr/src/cgroup_manager.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ #include "cgroup_manager.h" -#include #include #include #include @@ -115,17 +114,8 @@ int WriteValue(int fd, int v, bool newLine = true) } // namespace -CgroupManager::CgroupManager() : memoryEventControlFd_(-1) -{ - for (int i = 0; i < SCHED_POLICY_MAX; ++i) { - cpusetTasksFds_[i] = -1; - } - - for (int i = 0; i < LOW_MEMORY_LEVEL_MAX; ++i) { - memoryEventFds_[i] = -1; - memoryPressureFds_[i] = -1; - } -} +CgroupManager::CgroupManager() +{} CgroupManager::~CgroupManager() { @@ -145,7 +135,7 @@ CgroupManager::~CgroupManager() close(memoryEventControlFd_); } - for (int i = 0; i < SCHED_POLICY_MAX; ++i) { + for (int i = 0; i < SCHED_POLICY_CPU_MAX; ++i) { if (cpusetTasksFds_[i] >= 0) { close(cpusetTasksFds_[i]); } @@ -166,12 +156,12 @@ bool CgroupManager::Init() return false; } - UniqueFd cpusetTasksFds[SCHED_POLICY_MAX]; + UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_MAX]; if (!InitCpusetTasksFds(cpusetTasksFds)) { return false; } - UniqueFd cpuctlTasksFds[SCHED_POLICY_MAX]; + UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_MAX]; if (!InitCpuctlTasksFds(cpuctlTasksFds)) { return false; } @@ -357,7 +347,12 @@ void CgroupManager::OnReadable(int32_t fd) return false; } if (count < 1) { - APP_LOGW("%{public}s(%{public}d) invalid eventfd count %{public}" PRIu64 ".", __func__, __LINE__, count); +#if BINDER_IPC_32BIT + APP_LOGW("%{public}s(%{public}d) invalid eventfd count %{public}llu.", __func__, __LINE__, count); +#else + APP_LOGW("%{public}s(%{public}d) invalid eventfd count %{public}lu.", __func__, __LINE__, count); +#endif + return false; } APP_LOGW( diff --git a/services/appmgr/src/lmks/lmks_server.cpp b/services/appmgr/src/lmks/lmks_server.cpp index 59a33fbe3ac88e58b2f5144faa00c89e0c7078ff..0b89cd3d6b25825b1095fea685cbd6c4fa972148 100644 --- a/services/appmgr/src/lmks/lmks_server.cpp +++ b/services/appmgr/src/lmks/lmks_server.cpp @@ -28,25 +28,28 @@ namespace OHOS { namespace LMKS { namespace { +#ifdef __MUSL__ +const std::string LMKS_SOCKET_NAME = "/dev/unix/socket/lmks"; +#else const std::string LMKS_SOCKET_NAME = "/dev/socket/lmks"; -constexpr uint32_t LISTEN_CLIENTS = 5; // 5: max num of clients -constexpr uint32_t WAIT_DELAY_US = 100 * 1000; // 100ms +#endif +constexpr uint32_t LISTEN_CLIENTS = 5; // 5: max num of clients +constexpr uint32_t WAIT_DELAY_US = 100 * 1000; // 100ms constexpr int LMKS_CMD_TARGET = 0; constexpr int LMKS_CMD_PROCPRIO = 1; constexpr int LMKS_CMD_PROCREMOVE = 2; constexpr int LMKS_CMD_PROCPURGE = 3; -constexpr uid_t LMKS_ID_ROOT = 0; // chown owner -constexpr gid_t LMKS_ID_SYSTEM = 1000; // chown group -constexpr mode_t SOCKET_PERM = 0666; // root system can read and write lmks socket +constexpr uid_t LMKS_ID_ROOT = 0; // chown owner +constexpr gid_t LMKS_ID_SYSTEM = 1000; // chown group +constexpr mode_t SOCKET_PERM = 0666; // root system can read and write lmks socket constexpr struct timeval SOCKET_TIMEOUT = {5, 0}; // 5, 0: { 5 sec, 0 msec } for timeout } // namespace using namespace OHOS::HiviewDFX; static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "LmksServer"}; -LmksServer::LmksServer() - : isStart_(false), socketFd_(-1), socketAddrLen_(0), lmksUtils_(nullptr) +LmksServer::LmksServer() : isStart_(false), socketFd_(-1), socketAddrLen_(0), lmksUtils_(nullptr) { memset_s(&socketAddr_, sizeof(socketAddr_), 0, sizeof(socketAddr_)); } @@ -59,7 +62,7 @@ LmksServer::~LmksServer() void LmksServer::StartServer() { if (isStart_) { - HiLog::Error(LABEL, "Lmks server has started."); + HiLog::Error(LABEL, "Lmks server has started."); return; } @@ -81,7 +84,7 @@ void LmksServer::StartServer() } LMKS_PACKET cmds; - int len = RecvSocketMessage(connectFd, (void*)cmds, sizeof(cmds)); + int len = RecvSocketMessage(connectFd, (void *)cmds, sizeof(cmds)); if (len <= 0) { HiLog::Error(LABEL, "Failed to read socket message, len %{public}d", len); close(connectFd); @@ -114,7 +117,7 @@ int LmksServer::RegisterSocket() } if (strcpy_s(socketAddr_.sun_path, sizeof(socketAddr_.sun_path), LMKS_SOCKET_NAME.c_str()) != 0) { - HiLog::Error(LABEL, "Failed to snprint32_tf_s socket addr, err %{public}s", strerror(errno)); + HiLog::Error(LABEL, "Failed to snprint32_tf_s socket addr, err %{public}s", strerror(errno)); return (-errno); } @@ -160,7 +163,8 @@ int LmksServer::RegisterSocket() return 0; } -int LmksServer::WaitConnection() { +int LmksServer::WaitConnection() +{ if (socketFd_ < 0) { HiLog::Error(LABEL, "lmks server not register."); return -1; @@ -168,6 +172,7 @@ int LmksServer::WaitConnection() { struct sockaddr_un clientAddr; socklen_t clientLen = sizeof(clientAddr); + if (memset_s(&clientAddr, clientLen, 0, clientLen) != 0) { HiLog::Warn(LABEL, "Failed to memset client addr, err %{public}s", strerror(errno)); } @@ -181,6 +186,7 @@ int LmksServer::WaitConnection() { if ((setsockopt(connFd, SOL_SOCKET, SO_RCVTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) < 0) || (setsockopt(connFd, SOL_SOCKET, SO_SNDTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) < 0)) { HiLog::Error(LABEL, "Failed to set opt of Connection %d, err %{public}s", connFd, strerror(errno)); + close(connFd); return (-errno); } @@ -236,7 +242,8 @@ int LmksServer::RecvSocketMessage(int connectFd, void *buf, int len) void LmksServer::ProcessMessage(int connectFd, LMKS_PACKET cmds, int len) { if (!isStart_ || (lmksUtils_ == nullptr)) { - HiLog::Error(LABEL, "Lmks server not start isStart_ %{public}d lmksUtils_%{public}p", isStart_, lmksUtils_.get()); + HiLog::Error( + LABEL, "Lmks server not start isStart_ %{public}d lmksUtils_%{public}p", isStart_, lmksUtils_.get()); close(connectFd); return; } @@ -250,27 +257,27 @@ void LmksServer::ProcessMessage(int connectFd, LMKS_PACKET cmds, int len) int ret = -1; pid_t pid = 0; - switch(cmds[0]){ - case LMKS_CMD_TARGET: - HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_TARGET "); - break; - case LMKS_CMD_PROCPRIO: - HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCPRIO"); - break; - case LMKS_CMD_PROCREMOVE: - HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCREMOVE"); - pid = cmds[1]; - ret = lmksUtils_->RemoveProcess(pid); - if (SendSocketMessage(connectFd, &ret, sizeof(ret)) <= 0){ - HiLog::Error(LABEL, "Failed to return the result of remove process"); - } - break; - case LMKS_CMD_PROCPURGE: - HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCPURGE"); - break; - default: - HiLog::Error(LABEL, "Wrong cmd %d", cmds[0]); - break; + switch (cmds[0]) { + case LMKS_CMD_TARGET: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_TARGET "); + break; + case LMKS_CMD_PROCPRIO: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCPRIO"); + break; + case LMKS_CMD_PROCREMOVE: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCREMOVE"); + pid = cmds[1]; + ret = lmksUtils_->RemoveProcess(pid); + if (SendSocketMessage(connectFd, &ret, sizeof(ret)) <= 0) { + HiLog::Error(LABEL, "Failed to return the result of remove process"); + } + break; + case LMKS_CMD_PROCPURGE: + HiLog::Info(LABEL, "ProcessMessage LMKS_CMD_PROCPURGE"); + break; + default: + HiLog::Error(LABEL, "Wrong cmd %d", cmds[0]); + break; } // close connect fd. diff --git a/services/appmgr/src/lmks/lmks_utils.cpp b/services/appmgr/src/lmks/lmks_utils.cpp index 1066ee8d8d51b8619a4f71b48a6754701968211f..1c373b0807e15ec0e9b28c33c6d55c299db1a89d 100644 --- a/services/appmgr/src/lmks/lmks_utils.cpp +++ b/services/appmgr/src/lmks/lmks_utils.cpp @@ -60,7 +60,8 @@ int LmksUtils::RemoveProcess(pid_t pid) HiLog::Warn(LABEL, "kill pid %{public}d err %{public}s", pid, strerror(errno)); return (-errno); } else { - HiLog::Info(LABEL, "kill pid %{public}d success, name %{public}s size %{public}d", pid, procName.c_str(), procSize); + HiLog::Info( + LABEL, "kill pid %{public}d success, name %{public}s size %{public}d", pid, procName.c_str(), procSize); } return 0; @@ -103,11 +104,11 @@ std::string LmksUtils::GetProcName(pid_t pid) ret = ReadAll(fd, line, sizeof(line) - 1); if (ret < 0) { - close(fd); + close(fd); return name; } - if (strlen(line) != 0) { + if (strlen(line) < PROC_LINE_MAX && strlen(line) != 0) { name = line; } else { HiLog::Error(LABEL, "cmdline no data"); @@ -159,8 +160,7 @@ int LmksUtils::GetProcSize(pid_t pid) return -1; } - if ((strlen(line) != 0) && - (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { + if ((strlen(line) < PROC_LINE_MAX && strlen(line) != 0) && (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { HiLog::Info(LABEL, "pid %{public}d total %{public}d rss %{public}d", pid, total, rss); } else { HiLog::Error(LABEL, "strlen or sscanf_s err %{public}s", strerror(errno)); @@ -193,5 +193,5 @@ ssize_t LmksUtils::ReadAll(int fd, char *buf, size_t maxLen) return ret; } -} // namespace AppExecFwk +} // namespace LMKS } // namespace OHOS diff --git a/services/appmgr/src/process_optimizer.cpp b/services/appmgr/src/process_optimizer.cpp index da02f7a07a5ed7862ec4fb870ac8455c79a9e57e..96a9340a6e9c0ef4cf65718ce053c5800e77af0b 100644 --- a/services/appmgr/src/process_optimizer.cpp +++ b/services/appmgr/src/process_optimizer.cpp @@ -700,7 +700,7 @@ void ProcessOptimizer::SetAppFreezingTime(int time) { APP_LOGE("%{public}s input second time:[%{public}d]", __func__, time); - if (time < 0) { + if (time > APP_SUSPEND_TIMEOUT_MAX && time < 0) { APP_LOGE("%{public}s input time error.", __func__); return; } diff --git a/services/appmgr/test/mock/include/mock_bundle_manager.h b/services/appmgr/test/mock/include/mock_bundle_manager.h index 312d5f4182e1e5303e1f48f55ea2178db480cfd5..4dfc90f9875ae1878049d89f74cd7c6fa85c58c2 100644 --- a/services/appmgr/test/mock/include/mock_bundle_manager.h +++ b/services/appmgr/test/mock/include/mock_bundle_manager.h @@ -60,6 +60,10 @@ public: { return true; }; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override { return true; @@ -174,6 +178,16 @@ public: { return nullptr; }; + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override + { + return true; + } }; class BundleMgrStub : public IRemoteStub { @@ -214,6 +228,10 @@ public: { return true; }; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override { @@ -328,7 +346,8 @@ public: { return true; } - virtual bool GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) override + virtual bool GetFormsInfoByModule( + const std::string &bundleName, const std::string &moduleName, std::vector &formInfos) override { return true; } @@ -336,6 +355,15 @@ public: { return true; } + virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override + { + return true; + } }; } // namespace AppExecFwk diff --git a/services/appmgr/test/mock/src/mock_bundle_manager.cpp b/services/appmgr/test/mock/src/mock_bundle_manager.cpp index 7befaaed6dd0913f4ffa442cde57e3ac7b50102b..e9d6280bf9d73b58770c010ce6cf1d08017c9124 100644 --- a/services/appmgr/test/mock/src/mock_bundle_manager.cpp +++ b/services/appmgr/test/mock/src/mock_bundle_manager.cpp @@ -28,6 +28,7 @@ bool BundleMgrProxy::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abil if (eleName.GetBundleName().empty()) { return false; } + abilityInfo.visible = true; abilityInfo.name = eleName.GetAbilityName(); abilityInfo.bundleName = eleName.GetBundleName(); abilityInfo.applicationName = "Helloworld"; @@ -70,6 +71,7 @@ bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &ab if (std::string::npos != elementName.GetBundleName().find("service")) { abilityInfo.type = AppExecFwk::AbilityType::SERVICE; } + abilityInfo.visible = true; abilityInfo.name = elementName.GetAbilityName(); abilityInfo.bundleName = elementName.GetBundleName(); abilityInfo.applicationName = elementName.GetBundleName(); diff --git a/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp b/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp index 6b45f6bb00a39d1072ddba6f99dcf28c0c181fee..2b7a5ac48b4ceb819bc70ecc2957a54e2b3cd82e 100644 --- a/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp +++ b/services/appmgr/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp @@ -183,7 +183,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_001, TestSize.L sptr token = new MockAbilityToken(); auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); - ASSERT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(abilityRunningRecord != nullptr); abilityRunningRecord->SetState(AbilityState::ABILITY_STATE_READY); appRunningRecord->SetState(ApplicationState::APP_STATE_READY); @@ -216,7 +216,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_002, TestSize.L sptr token = new MockAbilityToken(); auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); - ASSERT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(abilityRunningRecord != nullptr); AbilityState state = abilityRunningRecord->GetState(); appRunningRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_END); @@ -241,7 +241,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_003, TestSize.L abilityInfo->name = GetTestAbilityName(); sptr token = new MockAbilityToken(); auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); - ASSERT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(abilityRunningRecord != nullptr); AbilityState state = abilityRunningRecord->GetState(); @@ -272,7 +272,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_004, TestSize.L sptr token2 = new MockAbilityToken(); auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); - ASSERT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(abilityRunningRecord != nullptr); AbilityState state = abilityRunningRecord->GetState(); EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token2) == nullptr); @@ -304,8 +304,8 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_005, TestSize.L auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); auto anotherAbilityRunningRecord = appRunningRecord->AddAbility(anotherToken, anotherAbilityInfo); - ASSERT_TRUE(abilityRunningRecord != nullptr); - ASSERT_TRUE(anotherAbilityRunningRecord != nullptr); + EXPECT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(anotherAbilityRunningRecord != nullptr); anotherAbilityRunningRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); appRunningRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); @@ -373,7 +373,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, UpdateAbilityRunningRecord_007, TestSize.L auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); auto anotherAbilityRunningRecord = appRunningRecord->AddAbility(anotherToken, anotherAbilityInfo); EXPECT_TRUE(abilityRunningRecord != nullptr); - ASSERT_TRUE(anotherAbilityRunningRecord != nullptr); + EXPECT_TRUE(anotherAbilityRunningRecord != nullptr); anotherAbilityRunningRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); appRunningRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); abilityRunningRecord->SetState(AbilityState::ABILITY_STATE_BACKGROUND); @@ -406,7 +406,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_001, TestSize.L auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); EXPECT_TRUE(abilityRunningRecord != nullptr); - ASSERT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); appRunningRecord->ClearAbility(abilityRunningRecord); EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) == nullptr); @@ -431,7 +431,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, DeleteAbilityRunningRecord_002, TestSize.L auto abilityRunnningRecord = appRunningRecord->AddAbility(token, abilityInfo); EXPECT_TRUE(abilityRunnningRecord != nullptr); - ASSERT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); + EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); appRunningRecord->ClearAbility(nullptr); EXPECT_TRUE(appRunningRecord->GetAbilityRunningRecordByToken(token) != nullptr); @@ -517,7 +517,7 @@ HWTEST_F(AmsAbilityRunningRecordTest, SetGetAbilityRecord_001, TestSize.Level0) sptr token = new MockAbilityToken(); auto abilityRunningRecord = appRunningRecord->AddAbility(token, abilityInfo); - ASSERT_TRUE(abilityRunningRecord != nullptr); + EXPECT_TRUE(abilityRunningRecord != nullptr); abilityRunningRecord->SetVisibility(1); abilityRunningRecord->SetPerceptibility(1); abilityRunningRecord->SetConnectionState(1); diff --git a/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp index 74f5053434c3669967a1f196344684c4d043f09d..e6582b38210b9fd7fc992350ea29434b98096016 100644 --- a/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp +++ b/services/appmgr/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp @@ -90,6 +90,7 @@ void AmsWorkFlowTest::TearDown() AbilityInfo AmsWorkFlowTest::CreateAbilityInfo(const std::string &ability, const std::string &app) const { AbilityInfo abilityInfo; + abilityInfo.visible = true; abilityInfo.name = "test_ability" + ability; abilityInfo.applicationName = "test_app" + app; return abilityInfo; diff --git a/services/appmgr/test/unittest/ams_process_optimizer_test/ams_process_optimizer_test.cpp b/services/appmgr/test/unittest/ams_process_optimizer_test/ams_process_optimizer_test.cpp index 49686a5c44a78f27c7a14f2b7a9dda5a28aaeb88..bad957fbc5506d31b6ee9310fd0be8a2c63611c3 100644 --- a/services/appmgr/test/unittest/ams_process_optimizer_test/ams_process_optimizer_test.cpp +++ b/services/appmgr/test/unittest/ams_process_optimizer_test/ams_process_optimizer_test.cpp @@ -1,3 +1,17 @@ +/* + * Copyright (c) 2021 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 #define private public diff --git a/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp b/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp index b8c9c1a8b00b78ba2ad20f34a563957926672491..1364cffb53dd6d6ef2e9e84d81c896d002e599b5 100644 --- a/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp +++ b/services/appmgr/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp @@ -104,7 +104,7 @@ void AmsRecentAppListTest::StartProcessSuccess(const int32_t index) const auto appInfo = GetApplicationByIndex(index); sptr token = new (std::nothrow) MockAbilityToken(); MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); - ASSERT_TRUE(mockClientPtr); + EXPECT_TRUE(mockClientPtr); // mock start process success, and pid is right. EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); @@ -150,7 +150,7 @@ HWTEST_F(AmsRecentAppListTest, Create_002, TestSize.Level1) // mock start process failed. MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); - ASSERT_TRUE(mockClientPtr); + EXPECT_TRUE(mockClientPtr); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).WillOnce(Return(ERR_APPEXECFWK_ASSEMBLE_START_MSG_FAILED)); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); @@ -175,7 +175,7 @@ HWTEST_F(AmsRecentAppListTest, Create_003, TestSize.Level1) auto appInfo = GetApplicationByIndex(INDEX_NUM_1); sptr token = new (std::nothrow) MockAbilityToken(); MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); - ASSERT_TRUE(mockClientPtr); + EXPECT_TRUE(mockClientPtr); // mock start process success, and pid is right. EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); @@ -370,7 +370,7 @@ HWTEST_F(AmsRecentAppListTest, RecentAppList_001, TestSize.Level1) auto appInfo = GetApplicationByIndex(INDEX_NUM_1); sptr token = new (std::nothrow) MockAbilityToken(); MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); - ASSERT_TRUE(mockClientPtr); + EXPECT_TRUE(mockClientPtr); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); @@ -398,7 +398,7 @@ HWTEST_F(AmsRecentAppListTest, PushAppFront_001, TestSize.Level1) auto appInfo = GetApplicationByIndex(INDEX_NUM_1); sptr token = new (std::nothrow) MockAbilityToken(); MockAppSpawnClient *mockClientPtr = new (std::nothrow) MockAppSpawnClient(); - ASSERT_TRUE(mockClientPtr); + EXPECT_TRUE(mockClientPtr); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(pid), Return(ERR_OK))); serviceInner_->SetAppSpawnClient(std::unique_ptr(mockClientPtr)); diff --git a/services/bundlemgr/BUILD.gn b/services/bundlemgr/BUILD.gn old mode 100644 new mode 100755 index 39078241eb3d30f05e8b6613597300a5eb431e8a..e786a2a14ac476f4623f683e03af044a64a3e6d4 --- a/services/bundlemgr/BUILD.gn +++ b/services/bundlemgr/BUILD.gn @@ -121,6 +121,7 @@ ohos_shared_library("libbms") { "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//base/notification/ces_standard/interfaces/innerkits/native/include", "//utils/system/safwk/native/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -133,6 +134,8 @@ ohos_shared_library("libbms") { "src/bundle_scanner.cpp", "src/bundle_status_callback_death_recipient.cpp", "src/kvstore_death_recipient_callback.cpp", + "src/module_usage_data_storage.cpp", + "src/permission_changed_death_recipient.cpp", "src/system_ability_helper.cpp", ] @@ -163,6 +166,7 @@ ohos_shared_library("libbms") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ @@ -196,6 +200,7 @@ ohos_executable("installs") { ":parser_common", "${common_path}:libappexecfwk_common", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ diff --git a/services/bundlemgr/include/base_bundle_installer.h b/services/bundlemgr/include/base_bundle_installer.h index 22d0871bf41a10685473e3ddac06f5d35e625520..266ba2b411ec64569d5d62d02510721c6482e6b9 100644 --- a/services/bundlemgr/include/base_bundle_installer.h +++ b/services/bundlemgr/include/base_bundle_installer.h @@ -106,32 +106,36 @@ private: * to install or update. * @param installParam Indicates the install parameters. * @param appType Indicates the application type. + * @param uid Indicates the uid of the application. * @return Returns ERR_OK if the bundle install successfully; returns error code otherwise. */ - ErrCode ProcessBundleInstall( - const std::string &bundlePath, const InstallParam &installParam, const Constants::AppType appType); + ErrCode ProcessBundleInstall(const std::string &bundlePath, const InstallParam &installParam, + const Constants::AppType appType, int32_t &uid); /** * @brief The real procedure function for uninstall a bundle. * @param bundleName Indicates the bundle name of the application to uninstall. * @param installParam Indicates the uninstall parameters. + * @param uid Indicates the uid of the application. * @return Returns ERR_OK if the bundle uninstall successfully; returns error code otherwise. */ - ErrCode ProcessBundleUninstall(const std::string &bundleName, const InstallParam &installParam); + ErrCode ProcessBundleUninstall(const std::string &bundleName, const InstallParam &installParam, int32_t &uid); /** * @brief The real procedure for uninstall a module in a specific bundle. * @param bundleName Indicates the bundle name of the application to uninstall. * @param modulePackage Indicates the module package of the module to uninstall. * @param installParam Indicates the uninstall parameters. + * @param uid Indicates the uid of the application. * @return Returns ERR_OK if the module uninstall successfully; returns error code otherwise. */ - ErrCode ProcessBundleUninstall( - const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam); + ErrCode ProcessBundleUninstall(const std::string &bundleName, const std::string &modulePackage, + const InstallParam &installParam, int32_t &uid); /** * @brief The process of installing a new bundle. * @param info Indicates the InnerBundleInfo parsed from the config.json in the HAP package. + * @param uid Indicates the uid of the application. * @return Returns ERR_OK if the new bundle install successfully; returns error code otherwise. */ - ErrCode ProcessBundleInstallStatus(InnerBundleInfo &info); + ErrCode ProcessBundleInstallStatus(InnerBundleInfo &info, int32_t &uid); /** * @brief The process of updating an exist bundle. * @param oldInfo Indicates the exist InnerBundleInfo object get from the database. diff --git a/services/bundlemgr/include/bundle_data_mgr.h b/services/bundlemgr/include/bundle_data_mgr.h index 0a962c6856e4ed28e8d0f2e4c212c73449248336..7f78b68d152471f7f2f5b05c2d6ecf14084cba1f 100755 --- a/services/bundlemgr/include/bundle_data_mgr.h +++ b/services/bundlemgr/include/bundle_data_mgr.h @@ -21,6 +21,7 @@ #include #include #include +#include #include "ohos/aafwk/content/want.h" @@ -29,6 +30,10 @@ #include "inner_bundle_info.h" #include "bundle_status_callback_interface.h" #include "bundle_data_storage_interface.h" +#include "module_usage_record.h" +#include "module_usage_data_storage.h" +#include "on_permission_changed_callback_interface.h" +#include "common_event_manager.h" namespace OHOS { namespace AppExecFwk { @@ -119,6 +124,13 @@ public: * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. */ bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) const; + /** + * @brief Query a AbilityInfo of list by the given Want. + * @param want Indicates the information of the ability. + * @param abilityInfo Indicates the obtained AbilityInfo of list. + * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. + */ + bool QueryAbilityInfos(const Want &want, std::vector &abilityInfo) const; /** * @brief Query the AbilityInfo by ability.uri in config.json. * @param abilityUri Indicates the uri of the ability. @@ -306,10 +318,11 @@ public: * @param resultCode Indicates the status code returned for the application installation, update, or uninstall * result. * @param type Indicates the NotifyType object. + * @param uid Indicates the uid of the application. * @return Returns true if this function is successfully called; returns false otherwise. */ bool NotifyBundleStatus(const std::string &bundleName, const std::string &modulePackage, - const std::string &mainAbility, const ErrCode resultCode, const NotifyType type); + const std::string &mainAbility, const ErrCode resultCode, const NotifyType type, const int32_t &uid); /** * @brief Get a mutex for locking by bundle name. * @param bundleName Indicates the bundle name. @@ -379,6 +392,72 @@ public: * @return Returns true if this function is successfully called; returns false otherwise. */ bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) const; + /** + * @brief Notify a specified ability for activity. + * @param bundleName Indicates the bundle name of the ability to activity. + * @param abilityName Indicates the name of the ability to activity. + * @param launchTime Indicates the ability launchTime. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) const; + /** + * @brief Query ModuleUsageRecord objects ordered by lastLaunchTime desc + * @param maxNum Indicates the max number ShortcutInfo objects to get. + * @param records List of ModuleUsageRecord objects if obtained. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetUsageRecords(int32_t maxNum, std::vector &records); + /** + * @brief Registers a callback for listening for permission changes of all UIDs. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool RegisterAllPermissionsChanged(const sptr &callback); + /** + * @brief Registers a callback for listening for permission changes of specified UIDs. + * @param uids Indicates the list of UIDs whose permission changes will be monitored. + * @param callback Indicates the callback method to register. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool RegisterPermissionsChanged(const std::vector &uids, const sptr &callback); + /** + * @brief Add death recipient for specified callback registerd. + * @param callback Indicates the callback for death recipient. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool AddDeathRecipient(const sptr &callback); + /** + * @brief Unregisters a specified callback for listening for permission changes. + * @param callback Indicates the callback method to unregister. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UnregisterPermissionsChanged(const sptr &callback); + /** + * @brief Call callback for listening the uid permission changes. + * @param uid Indicates the bundle uid whose permission changes. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool NotifyPermissionsChanged(int32_t uid); + /** + * @brief Update bundle usage record on bundle removed. + * @param keepUsage Indicates the flag record is remove on bundle removed. + * @param userId Indicates the user Id of the application. + * @param bundleName Indicates the bundle name of the application. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UpdateUsageRecordOnBundleRemoved(bool keepUsage, const int userId, const std::string &bundleName) const; + /** + * @brief Update bundle usage record on module removed. + * @param keepUsage Indicates the flag record is remove on module removed. + * @param userId Indicates the user Id of the application. + * @param bundleName Indicates the bundle name of the application. + * @param moduleName Indicates the module name of the application. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UpdateUsageRecordOnModuleRemoved( + bool keepUsage, const int userId, const std::string &bundleName, const std::string &moduleName) const; + private: /** * @brief Init transferStates. @@ -429,6 +508,8 @@ private: mutable std::mutex uidMapMutex_; mutable std::mutex callbackMutex_; mutable std::shared_mutex bundleMutex_; + mutable std::mutex allPermissionsChangedLock_; + mutable std::mutex permissionsChangedLock_; bool allInstallFlag_ = false; // using for locking by bundleName std::unordered_map bundleMutexMap_; @@ -447,6 +528,10 @@ private: // current-status:previous-statue pair std::multimap transferStates_; std::shared_ptr dataStorage_; + std::shared_ptr usageRecordStorage_; + std::set> allPermissionsCallbacks_; + // map. + std::map>> permissionsCallbacks_; }; } // namespace AppExecFwk diff --git a/services/bundlemgr/include/bundle_mgr_host_impl.h b/services/bundlemgr/include/bundle_mgr_host_impl.h index aba344a3999f2e8503bbcf2a15d1d8767952ee97..8c2b84b3afd8a1186bf0dbaf85dffb197fb9bd91 100644 --- a/services/bundlemgr/include/bundle_mgr_host_impl.h +++ b/services/bundlemgr/include/bundle_mgr_host_impl.h @@ -108,6 +108,13 @@ public: * @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise. */ virtual bool QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) override; + /** + * @brief Query the AbilityInfo of list by the given Want. + * @param want Indicates the information of the ability. + * @param abilityInfos Indicates the obtained AbilityInfos object. + * @return Returns true if the AbilityInfos is successfully obtained; returns false otherwise. + */ + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override; /** * @brief Query the AbilityInfo by ability.uri in config.json. * @param abilityUri Indicates the uri of the ability. @@ -357,6 +364,23 @@ public: * @return Returns true if GetShortcutInfos successfully; returns false otherwise. */ virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) override; + /** + * @brief Get module usage record list in descending order of lastLaunchTime. + * @param maxNum the return size of the records, must be in range of 1 to 1000. + * @param moduleUsageRecords List of ModuleUsageRecord objects if obtained. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) override; + /** + * @brief Notify a specified ability for activity. + * @param bundleName Indicates the bundle name of the ability to activity. + * @param abilityName Indicates the name of the ability to activity. + * @param launchTime Indicates the ability launchTime. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override; + private: const std::shared_ptr GetDataMgrFromService(); }; diff --git a/services/bundlemgr/include/bundle_mgr_service.h b/services/bundlemgr/include/bundle_mgr_service.h index d2308c6c1f60d06d72d6e6b0b586c1c256b57617..5482114b8dc44c66ea9a03fa590a4e1063b55fd4 100644 --- a/services/bundlemgr/include/bundle_mgr_service.h +++ b/services/bundlemgr/include/bundle_mgr_service.h @@ -25,6 +25,7 @@ #include "bundle_installer_host.h" #include "bundle_mgr_host_impl.h" #include "bundle_mgr_service_event_handler.h" +#include "bundle_permissions_changed_monitor.h" namespace OHOS { namespace AppExecFwk { @@ -81,6 +82,7 @@ private: std::shared_ptr dataMgr_; sptr host_; sptr installer_; + std::shared_ptr perChangeSub_; DISALLOW_COPY_AND_MOVE(BundleMgrService); }; diff --git a/services/bundlemgr/include/bundle_permissions_changed_monitor.h b/services/bundlemgr/include/bundle_permissions_changed_monitor.h new file mode 100644 index 0000000000000000000000000000000000000000..a128d4a09cb2fbba3a050a0f64a9dde7e0efd9fb --- /dev/null +++ b/services/bundlemgr/include/bundle_permissions_changed_monitor.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_PERMISSIONS_CHANGED_MONITOR_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_PERMISSIONS_CHANGED_MONITOR_H +#include +#include "bundle_mgr_host.h" +#include "bundle_data_mgr.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "bundle_mgr_service.h" +#include "bundle_util.h" + +#include "bundle_data_mgr.h" +#include "json_serializer.h" +#include "app_log_wrapper.h" + + +#include "bundle_parser.h" +#include "installd_client.h" +#include "bundle_permission_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +class BundlePermissionsChangedMonitor : public EventFwk::CommonEventSubscriber { +public: + BundlePermissionsChangedMonitor(const std::shared_ptr &dataMgr, + const EventFwk::CommonEventSubscribeInfo& sp):CommonEventSubscriber(sp) + { + dataMgr_ = dataMgr; + } + ~BundlePermissionsChangedMonitor(){ + if(!dataMgr_){ + dataMgr_.reset(); + } + } + void OnReceiveEvent(const EventFwk::CommonEventData &data) + { + OHOS::AAFwk::Want want = data.GetWant(); + std::string action = want.GetAction(); + int32_t uid = data.GetCode(); + if ( dataMgr_ != nullptr && uid >=0 ) { + dataMgr_->NotifyPermissionsChanged(uid); + } + } +private: + std::shared_ptr dataMgr_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_BUNDLE_MONITOR_H \ No newline at end of file diff --git a/services/bundlemgr/include/common_profile.h b/services/bundlemgr/include/common_profile.h index 144b19fe044238f5e76b9dc986248d01ad747174..98624b7cf375907f0f1627e9d891d23bd9b2caee 100644 --- a/services/bundlemgr/include/common_profile.h +++ b/services/bundlemgr/include/common_profile.h @@ -32,6 +32,8 @@ const std::string PROFILE_KEY_LABEL_ID = "labelId"; const std::string PROFILE_KEY_DESCRIPTION = "description"; const std::string PROFILE_KEY_DESCRIPTION_ID = "descriptionId"; const std::string PROFILE_KEY_TYPE = "type"; +const std::string PROFILE_KEY_SRCPATH = "srcPath"; +const std::string PROFILE_KEY_SRCLANGUAGE = "srcLanguage"; // bundle profile tag const std::string BUNDLE_PROFILE_KEY_APP = "app"; @@ -121,6 +123,7 @@ const std::string BUNDLE_MODULE_PROFILE_KEY_CUSTOMIZE_DATA = "customizeData"; const std::string BUNDLE_MODULE_PROFILE_KEY_DELIVERY_WITH_INSTALL = "deliveryWithInstall"; const std::string BUNDLE_MODULE_PROFILE_KEY_MODULE_NAME = "moduleName"; const std::string BUNDLE_MODULE_PROFILE_KEY_MODULE_TYPE = "moduleType"; +const std::string BUNDLE_MODULE_PROFILE_KEY_MODULE_INSTALLATION_FREE = "installationFree"; // sub BUNDLE_MODULE_PROFILE_KEY_SKILLS const std::string BUNDLE_MODULE_PROFILE_KEY_ACTIONS = "actions"; const std::string BUNDLE_MODULE_PROFILE_KEY_ENTITIES = "entities"; @@ -190,6 +193,8 @@ const std::string BUNDLE_MODULE_PROFILE_FORMS_UPDATE_DURATION = "updateDuration" const std::string BUNDLE_MODULE_PROFILE_FORMS_DEEP_LINK = "deepLink"; const std::string BUNDLE_MODULE_PROFILE_FORMS_JS_COMPONENT_NAME = "jsComponentName"; const std::string BUNDLE_MODULE_PROFILE_FORMS_VALUE = "value"; +const std::string BUNDLE_MODULE_PROFILE_FORMS_FORM_CONFIG_ABILITY = "formConfigAbility"; +const std::string BUNDLE_MODULE_PROFILE_FORMS_FORM_VISIBLE_NOTIFY = "formEnabled"; // sub BUNDLE_MODULE_PROFILE_KEY_JS const std::string BUNDLE_MODULE_PROFILE_KEY_PAGES = "pages"; const std::string BUNDLE_MODULE_PROFILE_KEY_WINDOW = "window"; diff --git a/services/bundlemgr/include/inner_bundle_info.h b/services/bundlemgr/include/inner_bundle_info.h index d67c71738ea967be7e91873be6574e44662a96c7..f1c6749a20a927712da1a28f886b4ce0cb86e70d 100644 --- a/services/bundlemgr/include/inner_bundle_info.h +++ b/services/bundlemgr/include/inner_bundle_info.h @@ -37,6 +37,7 @@ struct Distro { bool deliveryWithInstall; std::string moduleName; std::string moduleType; + bool installationFree = false; }; struct DefPermission { @@ -66,8 +67,12 @@ struct InnerModuleInfo { std::string modulePath; std::string moduleDataDir; std::string moduleResPath; + std::string label; + int32_t labelId = 0; std::string description; + int32_t descriptionId = 0; bool isEntry; + bool installationFree; MetaData metaData; ModuleColorMode colorMode = ModuleColorMode::AUTO; Distro distro; @@ -108,7 +113,7 @@ enum class ArrayType { NOT_ARRAY, }; -template +template void CheckArrayType( const nlohmann::json &jsonObject, const std::string &key, dataType &data, ArrayType arrayType, int32_t &parseResult) { @@ -119,7 +124,7 @@ void CheckArrayType( } switch (arrayType) { case ArrayType::STRING: - for (const auto& array : arrays) { + for (const auto &array : arrays) { if (!array.is_string()) { APP_LOGE("array %{public}s is not string type", key.c_str()); parseResult = ERR_APPEXECFWK_PARSE_PROFILE_PROP_TYPE_ERROR; @@ -130,7 +135,7 @@ void CheckArrayType( } break; case ArrayType::OBJECT: - for (const auto& array : arrays) { + for (const auto &array : arrays) { if (!array.is_object()) { APP_LOGE("array %{public}s is not object type", key.c_str()); parseResult = ERR_APPEXECFWK_PARSE_PROFILE_PROP_TYPE_ERROR; @@ -142,7 +147,7 @@ void CheckArrayType( } break; case ArrayType::NUMBER: - for (const auto& array : arrays) { + for (const auto &array : arrays) { if (!array.is_number()) { APP_LOGE("array %{public}s is not number type", key.c_str()); parseResult = ERR_APPEXECFWK_PARSE_PROFILE_PROP_TYPE_ERROR; @@ -161,7 +166,7 @@ void CheckArrayType( } } -template +template void GetValueIfFindKey(const nlohmann::json &jsonObject, const nlohmann::detail::iter_impl &end, const std::string &key, dataType &data, JsonType jsonType, bool isNecessary, int32_t &parseResult, ArrayType arrayType) @@ -290,6 +295,12 @@ public: * @return Returns the AbilityInfo object if find it; returns null otherwise. */ std::optional FindAbilityInfo(const std::string &bundleName, const std::string &abilityName) const; + /** + * @brief Find abilityInfo of list by bundle name. + * @param bundleName Indicates the bundle name. + * @return Returns the AbilityInfo of list if find it; returns null otherwise. + */ + std::optional> FindAbilityInfos(const std::string &bundleName) const; /** * @brief Transform the InnerBundleInfo object to string. * @return Returns the string object @@ -322,23 +333,23 @@ public: * @param formInfos Indicates the Forms object to be add. * @return */ - void AddModuleFormInfo(const std::map> &formInfos) - { - for (const auto &forms : formInfos) { - formInfos_.try_emplace(forms.first, forms.second); - } - } + void AddModuleFormInfo(const std::map> &formInfos) + { + for (const auto &forms : formInfos) { + formInfos_.try_emplace(forms.first, forms.second); + } + } /** * @brief Add shortcut infos to old InnerBundleInfo object. * @param shortcutInfos Indicates the Shortcut object to be add. * @return */ - void AddModuleShortcutInfo(const std::map &shortcutInfos) - { - for (const auto &shortcut : shortcutInfos) { - shortcutInfos_.try_emplace(shortcut.first, shortcut.second); - } - } + void AddModuleShortcutInfo(const std::map &shortcutInfos) + { + for (const auto &shortcut : shortcutInfos) { + shortcutInfos_.try_emplace(shortcut.first, shortcut.second); + } + } /** * @brief Add innerModuleInfos to old InnerBundleInfo object. * @param innerModuleInfos Indicates the InnerModuleInfo object to be add. @@ -548,8 +559,14 @@ public: */ std::optional FindAbilityInfoByUri(const std::string &abilityUri) const { + APP_LOGI("Uri is %{public}s", abilityUri.c_str()); for (const auto &ability : baseAbilityInfos_) { - if (ability.second.uri == abilityUri) { + if (ability.second.uri.size() < Constants::DATA_ABILITY_URI_PREFIX.size()) { + continue; + } + auto configUri = ability.second.uri.substr(Constants::DATA_ABILITY_URI_PREFIX.size()); + APP_LOGI("configUri is %{public}s", configUri.c_str()); + if (configUri == abilityUri) { return ability.second; } } @@ -918,19 +935,19 @@ public: * @param keyName Indicates object as key. * @param formInfos Indicates the formInfo object as value. */ - void InsertFormInfos(const std::string &keyName, const std::vector &formInfos) - { - formInfos_.emplace(keyName, formInfos); - } + void InsertFormInfos(const std::string &keyName, const std::vector &formInfos) + { + formInfos_.emplace(keyName, formInfos); + } /** * @brief Insert shortcutInfos. * @param keyName Indicates object as key. * @param shortcutInfos Indicates the shortcutInfos object as value. */ - void InsertShortcutInfos(const std::string &keyName, const ShortcutInfo &shortcutInfos) - { - shortcutInfos_.emplace(keyName, shortcutInfos); - } + void InsertShortcutInfos(const std::string &keyName, const ShortcutInfo &shortcutInfos) + { + shortcutInfos_.emplace(keyName, shortcutInfos); + } // use for new Info in updating progress void RestoreFromOldInfo(const InnerBundleInfo &oldInfo) { @@ -970,17 +987,22 @@ public: * @param moduleName Indicates the module name of the application. * @param formInfos List of FormInfo objects if obtained; */ - void GetFormsInfoByModule(const std::string &moduleName, std::vector &formInfos) const; + void GetFormsInfoByModule(const std::string &moduleName, std::vector &formInfos) const; /** * @brief Obtains the FormInfo objects provided by a specified application on the device. * @param formInfos List of FormInfo objects if obtained; */ - void GetFormsInfoByApp(std::vector &formInfos) const; + void GetFormsInfoByApp(std::vector &formInfos) const; /** * @brief Obtains the ShortcutInfo objects provided by a specified application on the device. * @param shortcutInfos List of ShortcutInfo objects if obtained. */ void GetShortcutInfos(std::vector &shortcutInfos) const; + + std::optional GetInnerModuleInfoByModuleName(const std::string &moduleName) const; + + void GetModuleNames(std::vector &moduleNames) const; + private: // using for get bool isSupportBackup_ = false; @@ -1000,7 +1022,7 @@ private: std::string currentPackage_; std::string mainAbilityName_; - std::map> formInfos_; + std::map> formInfos_; std::map baseAbilityInfos_; std::map innerModuleInfos_; std::map> skillInfos_; diff --git a/services/bundlemgr/include/module_usage_data_storage.h b/services/bundlemgr/include/module_usage_data_storage.h new file mode 100644 index 0000000000000000000000000000000000000000..d8c7e6a1598341f67666e3f1f25c441a5d32181b --- /dev/null +++ b/services/bundlemgr/include/module_usage_data_storage.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_MODULE_USAGE_DATA_STORAGE_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_MODULE_USAGE_DATA_STORAGE_H + +#include +#include + +#include "module_usage_record.h" + +#include "bundle_constants.h" +#include "distributed_kv_data_manager.h" +#include "inner_bundle_info.h" + + +namespace OHOS { +namespace AppExecFwk { +class DataMgr; + +class ModuleUsageRecordStorage : public std::enable_shared_from_this { +public: + ModuleUsageRecordStorage(); + virtual ~ModuleUsageRecordStorage(); + + // add&update + bool AddOrUpdateRecord(ModuleUsageRecord& data, const std::string& deviceId, int32_t userId); + bool DeleteRecordByUserId(int32_t userId); + bool DeleteUsageRecord(const InnerBundleInfo& data, int32_t userId); + bool MarkUsageRecordRemoved(const InnerBundleInfo &data, int32_t userId); + bool QueryRecordByNum(int32_t maxNum, std::vector& records, int32_t userId); + void SetDataMgr(const std::weak_ptr& dataMgr) const; + void OnKvStoreDeath(); + void RegisterKvStoreDeathListener(); +private: + + bool DeleteRecordByKeys(const std::string& bundleName, std::vector& keys); + bool QueryRecordByCondition(DistributedKv::DataQuery& query, std::vector& records); + void AbilityRecordToKey(const std::string& userId, const std::string& deviceId, + const std::string& bundleName, const std::string& moduleName, std::string& key) const; + void InnerBundleInfoToKeys(const InnerBundleInfo& data, int32_t userId, + std::vector& keys) const; + void FillDataStorageKeys(const std::string& userId, const std::string& bundleName, + const std::string& moduleName, std::vector& keys) const; + bool ParseKey(const std::string& key, ModuleUsageRecord& record) const; + void UpdateUsageRecord(const std::string& jsonString, ModuleUsageRecord& data); + void SaveEntries(const std::vector& allEntries, + std::vector& records) const; + void TryTwice(const std::function& func) const; + bool CheckKvStore(); + DistributedKv::Status GetKvStore(); + bool ResetKvStore(); + +private: + const DistributedKv::AppId appId_ { Constants::APP_ID }; + const DistributedKv::StoreId storeId_ { Constants::ABILITY_USAGE_STORE_ID }; + DistributedKv::DistributedKvDataManager dataManager_; + std::unique_ptr kvStorePtr_; + mutable std::mutex kvStorePtrMutex_; + enum { + DATABASE_KEY_INDEX_USER_ID = 0, + DATABASE_KEY_INDEX_DEVICE_ID, + DATABASE_KEY_INDEX_BUNDLE_NAME, + DATABASE_KEY_INDEX_MODULE_NAME, + DATABASE_KEY_INDEX_MAX_LENGTH, + }; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_MODULE_USAGE_DATA_STORAGE_H \ No newline at end of file diff --git a/services/bundlemgr/include/permission_changed_death_recipient.h b/services/bundlemgr/include/permission_changed_death_recipient.h new file mode 100644 index 0000000000000000000000000000000000000000..1f4e04072fbf3be8a4ceebf133acdeeab898a291 --- /dev/null +++ b/services/bundlemgr/include/permission_changed_death_recipient.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_PERMISSION_CHANGED_DEATH_RECIPIENT_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_PERMISSION_CHANGED_DEATH_RECIPIENT_H + +#include "iremote_object.h" + +#include "on_permission_changed_callback_interface.h" + +namespace OHOS { +namespace AppExecFwk { + +class PermissionChangedDeathRecipient : public IRemoteObject::DeathRecipient { + +public: + virtual void OnRemoteDied(const wptr& object) override; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_PERMISSION_CHANGED_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/bundlemgr/src/base_bundle_installer.cpp b/services/bundlemgr/src/base_bundle_installer.cpp index 77e367097b5710c86021c8e7a4d93fc291d968dc..023be8c65e14d3771b462f7b6b3c4d19fd261922 100755 --- a/services/bundlemgr/src/base_bundle_installer.cpp +++ b/services/bundlemgr/src/base_bundle_installer.cpp @@ -111,10 +111,15 @@ ErrCode BaseBundleInstaller::InstallBundle( APP_LOGI("begin to process %{public}s bundle install", bundlePath.c_str()); PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount()); - ErrCode result = ProcessBundleInstall(bundlePath, installParam, appType); + int32_t uid = Constants::INVALID_UID; + ErrCode result = ProcessBundleInstall(bundlePath, installParam, appType, uid); if (dataMgr_ && !bundleName_.empty() && !modulePackage_.empty()) { - dataMgr_->NotifyBundleStatus( - bundleName_, modulePackage_, mainAbility_, result, isAppExist_ ? NotifyType::UPDATE : NotifyType::INSTALL); + dataMgr_->NotifyBundleStatus(bundleName_, + modulePackage_, + mainAbility_, + result, + isAppExist_ ? NotifyType::UPDATE : NotifyType::INSTALL, + uid); } PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount()); @@ -127,10 +132,11 @@ ErrCode BaseBundleInstaller::UninstallBundle(const std::string &bundleName, cons APP_LOGD("begin to process %{public}s bundle uninstall", bundleName.c_str()); PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount()); - ErrCode result = ProcessBundleUninstall(bundleName, installParam); + int32_t uid = Constants::INVALID_UID; + ErrCode result = ProcessBundleUninstall(bundleName, installParam, uid); if (dataMgr_) { dataMgr_->NotifyBundleStatus( - bundleName, Constants::EMPTY_STRING, Constants::EMPTY_STRING, result, NotifyType::UNINSTALL_BUNDLE); + bundleName, Constants::EMPTY_STRING, Constants::EMPTY_STRING, result, NotifyType::UNINSTALL_BUNDLE, uid); } PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount()); @@ -144,10 +150,11 @@ ErrCode BaseBundleInstaller::UninstallBundle( APP_LOGD("begin to process %{public}s module in %{public}s uninstall", modulePackage.c_str(), bundleName.c_str()); PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount()); - ErrCode result = ProcessBundleUninstall(bundleName, modulePackage, installParam); + int32_t uid = Constants::INVALID_UID; + ErrCode result = ProcessBundleUninstall(bundleName, modulePackage, installParam, uid); if (dataMgr_) { dataMgr_->NotifyBundleStatus( - bundleName, modulePackage, Constants::EMPTY_STRING, result, NotifyType::UNINSTALL_MODULE); + bundleName, modulePackage, Constants::EMPTY_STRING, result, NotifyType::UNINSTALL_MODULE, uid); } PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount()); @@ -162,7 +169,7 @@ void BaseBundleInstaller::UpdateInstallerState(const InstallerState state) } ErrCode BaseBundleInstaller::ProcessBundleInstall( - const std::string &inBundlePath, const InstallParam &installParam, const Constants::AppType appType) + const std::string &inBundlePath, const InstallParam &installParam, const Constants::AppType appType, int32_t &uid) { APP_LOGI("ProcessBundleInstall bundlePath %{public}s", inBundlePath.c_str()); if (installParam.userId == Constants::INVALID_USERID) { @@ -179,9 +186,11 @@ ErrCode BaseBundleInstaller::ProcessBundleInstall( UpdateInstallerState(InstallerState::INSTALL_BUNDLE_CHECKED); Security::Verify::HapVerifyResult hapVerifyResult; - if (!BundleVerifyMgr::HapVerify(bundlePath, hapVerifyResult)) { - APP_LOGE("hap file verify failed"); - return ERR_APPEXECFWK_INSTALL_NO_SIGNATURE_INFO; + if (installParam.noCheckSignature == false) { + if (!BundleVerifyMgr::HapVerify(bundlePath, hapVerifyResult)) { + APP_LOGE("hap file verify failed"); + return ERR_APPEXECFWK_INSTALL_NO_SIGNATURE_INFO; + } } // parse the single bundle info to get the bundle name. @@ -190,9 +199,6 @@ ErrCode BaseBundleInstaller::ProcessBundleInstall( newInfo.SetAppType(appType); newInfo.SetUserId(installParam.userId); newInfo.SetIsKeepData(installParam.isKeepData); - auto provisionInfo = hapVerifyResult.GetProvisionInfo(); - newInfo.SetProvisionId(provisionInfo.appId); - if (!ModifyInstallDirByHapType(newInfo)) { APP_LOGE("modify bundle install dir failed %{public}d", result); return ERR_APPEXECFWK_INSTALL_PARAM_ERROR; @@ -202,8 +208,11 @@ ErrCode BaseBundleInstaller::ProcessBundleInstall( APP_LOGE("bundle parse failed %{public}d", result); return result; } - newInfo.SetAppFeature(provisionInfo.bundleInfo.appFeature); - + if (installParam.noCheckSignature == false) { + auto provisionInfo = hapVerifyResult.GetProvisionInfo(); + newInfo.SetProvisionId(provisionInfo.appId); + newInfo.SetAppFeature(provisionInfo.bundleInfo.appFeature); + } UpdateInstallerState(InstallerState::INSTALL_PARSED); bundleName_ = newInfo.GetBundleName(); @@ -226,13 +235,15 @@ ErrCode BaseBundleInstaller::ProcessBundleInstall( isAppExist_ = dataMgr_->GetInnerBundleInfo(bundleName_, Constants::CURRENT_DEVICE_ID, oldInfo); if (isAppExist_) { APP_LOGI("app is exist"); + uid = oldInfo.GetUid(); bool isReplace = (installParam.installFlag == InstallFlag::REPLACE_EXISTING); return ProcessBundleUpdateStatus(oldInfo, newInfo, isReplace); // app exist, but module may not } - return ProcessBundleInstallStatus(newInfo); + return ProcessBundleInstallStatus(newInfo, uid); } -ErrCode BaseBundleInstaller::ProcessBundleUninstall(const std::string &bundleName, const InstallParam &installParam) +ErrCode BaseBundleInstaller::ProcessBundleUninstall( + const std::string &bundleName, const InstallParam &installParam, int32_t &uid) { if (bundleName.empty()) { APP_LOGE("uninstall bundle name empty"); @@ -255,6 +266,7 @@ ErrCode BaseBundleInstaller::ProcessBundleUninstall(const std::string &bundleNam APP_LOGE("uninstall bundle info missing"); return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE; } + uid = oldInfo.GetUid(); ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); }); if (oldInfo.GetAppType() == Constants::AppType::SYSTEM_APP) { APP_LOGE("uninstall system app"); @@ -283,7 +295,7 @@ ErrCode BaseBundleInstaller::ProcessBundleUninstall(const std::string &bundleNam } ErrCode BaseBundleInstaller::ProcessBundleUninstall( - const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam) + const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam, int32_t &uid) { if (bundleName.empty() || modulePackage.empty()) { APP_LOGE("uninstall bundle name or module name empty"); @@ -306,6 +318,7 @@ ErrCode BaseBundleInstaller::ProcessBundleUninstall( APP_LOGE("uninstall bundle info missing"); return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE; } + uid = oldInfo.GetUid(); ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); }); if (oldInfo.GetAppType() == Constants::AppType::SYSTEM_APP) { @@ -369,7 +382,7 @@ ErrCode BaseBundleInstaller::RemoveBundle(InnerBundleInfo &info) return ERR_OK; } -ErrCode BaseBundleInstaller::ProcessBundleInstallStatus(InnerBundleInfo &info) +ErrCode BaseBundleInstaller::ProcessBundleInstallStatus(InnerBundleInfo &info, int32_t &uid) { APP_LOGI("ProcessBundleInstallStatus %{public}s", info.GetBundleName().c_str()); if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_START)) { @@ -382,6 +395,7 @@ ErrCode BaseBundleInstaller::ProcessBundleInstallStatus(InnerBundleInfo &info) APP_LOGE("create bundle and data dir failed"); return result; } + uid = info.GetUid(); UpdateInstallerState(InstallerState::INSTALL_CREATDIR); ScopeGuard bundleGuard([&] { RemoveBundleAndDataDir(info, false); }); diff --git a/services/bundlemgr/src/bundle_data_mgr.cpp b/services/bundlemgr/src/bundle_data_mgr.cpp index 53268c42bb9572e865561b664ace88e591c35e48..5d65fd7db940b4f13db6d8dd79a106c7044817e9 100755 --- a/services/bundlemgr/src/bundle_data_mgr.cpp +++ b/services/bundlemgr/src/bundle_data_mgr.cpp @@ -27,6 +27,7 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "bundle_status_callback_death_recipient.h" +#include "permission_changed_death_recipient.h" namespace OHOS { namespace AppExecFwk { @@ -34,9 +35,10 @@ namespace AppExecFwk { BundleDataMgr::BundleDataMgr() { InitStateTransferMap(); - if (!dataStorage_) { - dataStorage_ = std::make_shared(); - } + dataStorage_ = std::make_shared(); + usageRecordStorage_ = std::make_shared(); + // register distributed data process death listener. + usageRecordStorage_->RegisterKvStoreDeathListener(); APP_LOGI("BundleDataMgr instance is created"); } @@ -308,32 +310,98 @@ bool BundleDataMgr::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) return true; } +bool BundleDataMgr::QueryAbilityInfos(const Want &want, std::vector &abilityInfo) const +{ + ElementName element = want.GetElement(); + std::string abilityName = element.GetAbilityName(); + std::string bundleName = element.GetBundleName(); + APP_LOGI("bundle name:%{public}s, ability name:%{public}s", bundleName.c_str(), abilityName.c_str()); + + std::string keyName = bundleName + abilityName; + APP_LOGI("ability, name:%{public}s", keyName.c_str()); + std::lock_guard lock(bundleInfoMutex_); + if (bundleInfos_.empty()) { + APP_LOGI("bundleInfos_ is empty"); + return false; + } + auto item = bundleInfos_.find(bundleName); + if (item == bundleInfos_.end()) { + APP_LOGI("bundle:%{public}s not find", bundleName.c_str()); + return false; + } + + auto infoWithIdItem = item->second.find(Constants::CURRENT_DEVICE_ID); + if (infoWithIdItem == item->second.end()) { + APP_LOGI("bundle:%{public}s device id not find", bundleName.c_str()); + return false; + } + if (infoWithIdItem->second.IsDisabled()) { + APP_LOGI("app %{public}s is disabled", infoWithIdItem->second.GetBundleName().c_str()); + return false; + } + auto ability = infoWithIdItem->second.FindAbilityInfos(bundleName); + if (!ability) { + APP_LOGE("ability:%{public}s not find", keyName.c_str()); + return false; + } + abilityInfo = (*ability); + for (auto &ability : abilityInfo) { + infoWithIdItem->second.GetApplicationInfo( + ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, 0, ability.applicationInfo); + } + + return true; +} + bool BundleDataMgr::QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) const { - APP_LOGI("QueryAbilityInfoByUri"); + APP_LOGI("abilityUri is %{public}s", abilityUri.c_str()); if (abilityUri.empty()) { return false; } + if (abilityUri.find(Constants::DATA_ABILITY_URI_PREFIX) == std::string::npos) { + return false; + } std::lock_guard lock(bundleInfoMutex_); if (bundleInfos_.empty()) { APP_LOGI("bundleInfos_ data is empty"); return false; } + std::string noPpefixUri = abilityUri.substr(Constants::DATA_ABILITY_URI_PREFIX.size()); + auto posFirstSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR); + if (posFirstSeparator == std::string::npos) { + return false; + } + auto posSecondSeparator = noPpefixUri.find(Constants::DATA_ABILITY_URI_SEPARATOR, posFirstSeparator + 1); + std::string uri; + if (posSecondSeparator == std::string::npos) { + uri = noPpefixUri.substr(posFirstSeparator + 1, noPpefixUri.size() - posFirstSeparator - 1); + } else { + uri = noPpefixUri.substr(posFirstSeparator + 1, posSecondSeparator - posFirstSeparator - 1); + } + + std::string deviceId = noPpefixUri.substr(0, posFirstSeparator); + if (deviceId.empty()) { + deviceId = Constants::CURRENT_DEVICE_ID; + } for (const auto &item : bundleInfos_) { - for (const auto &info : item.second) { - if (info.second.IsDisabled()) { - APP_LOGI("app %{public}s is disabled", info.second.GetBundleName().c_str()); - continue; - } - auto ability = info.second.FindAbilityInfoByUri(abilityUri); - if (!ability) { - continue; - } - abilityInfo = (*ability); - info.second.GetApplicationInfo( - ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, 0, abilityInfo.applicationInfo); - return true; + auto infoWithIdItem = item.second.find(deviceId); + if (infoWithIdItem == item.second.end()) { + APP_LOGI("bundle device id:%{public}s not find", deviceId.c_str()); + return false; + } + if (infoWithIdItem->second.IsDisabled()) { + APP_LOGI("app %{public}s is disabled", infoWithIdItem->second.GetBundleName().c_str()); + continue; + } + auto ability = infoWithIdItem->second.FindAbilityInfoByUri(uri); + if (!ability) { + continue; } + abilityInfo = (*ability); + infoWithIdItem->second.GetApplicationInfo( + ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, 0, abilityInfo.applicationInfo); + return true; } return false; } @@ -1062,6 +1130,67 @@ bool BundleDataMgr::RecycleUidAndGid(const InnerBundleInfo &info) return true; } +bool BundleDataMgr::GetUsageRecords(const int32_t maxNum, std::vector &records) +{ + APP_LOGI("GetUsageRecords, maxNum: %{public}d", maxNum); + records.clear(); + std::vector usageRecords; + bool result = usageRecordStorage_->QueryRecordByNum(maxNum, usageRecords, 0); + if (!result) { + APP_LOGI("GetUsageRecords error"); + return false; + } + for (ModuleUsageRecord &item : usageRecords) { + APP_LOGD("GetUsageRecords item:%{public}s,%{public}s,%{public}s", + item.bundleName.c_str(), + item.name.c_str(), + item.abilityName.c_str()); + + std::lock_guard lock(bundleInfoMutex_); + if (bundleInfos_.empty()) { + APP_LOGI("bundleInfos_ data is empty"); + break; + } + auto infoItem = bundleInfos_.find(item.bundleName); + if (infoItem == bundleInfos_.end()) { + continue; + } + APP_LOGI("GetUsageRecords %{public}s", infoItem->first.c_str()); + auto bundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID); + if (bundleInfo == infoItem->second.end()) { + continue; + } + if (bundleInfo->second.IsDisabled()) { + APP_LOGI("app %{public}s is disabled", bundleInfo->second.GetBundleName().c_str()); + continue; + } + auto innerModuleInfo = bundleInfo->second.GetInnerModuleInfoByModuleName(item.name); + if (!innerModuleInfo) { + continue; + } + item.labelId = innerModuleInfo->labelId; + item.descriptionId = innerModuleInfo->descriptionId; + item.installationFreeSupported = innerModuleInfo->installationFree; + auto appInfo = bundleInfo->second.GetBaseApplicationInfo(); + item.appLabelId = appInfo.labelId; + auto ability = bundleInfo->second.FindAbilityInfo(item.bundleName, item.abilityName); + if (!ability) { + APP_LOGE("ability:%{public}s not find", item.abilityName.c_str()); + continue; + } + if (ability->type != AbilityType::PAGE) { + APP_LOGE("ability:%{public}s type is not PAGE", item.abilityName.c_str()); + continue; + } + item.abilityName = ability->name; + item.abilityLabelId = ability->labelId; + item.abilityDescriptionId = ability->descriptionId; + item.abilityIconId = ability->iconId; + records.emplace_back(item); + } + return true; +} + bool BundleDataMgr::RestoreUidAndGid() { // this function should be called with bundleInfoMutex_ locked @@ -1081,7 +1210,7 @@ bool BundleDataMgr::RestoreUidAndGid() } bool BundleDataMgr::NotifyBundleStatus(const std::string &bundleName, const std::string &modulePackage, - const std::string &mainAbility, const ErrCode resultCode, const NotifyType type) + const std::string &mainAbility, const ErrCode resultCode, const NotifyType type, const int32_t &uid) { APP_LOGI("notify type %{public}d with %{public}d for %{public}s-%{public}s in %{public}s", type, @@ -1130,6 +1259,8 @@ bool BundleDataMgr::NotifyBundleStatus(const std::string &bundleName, const std: element.SetBundleName(bundleName); element.SetAbilityName(mainAbility); want.SetElement(element); + want.SetParam(Constants::UID, uid); + APP_LOGI("want.SetParam uid %{public}d", uid); EventFwk::CommonEventData commonData{want}; EventFwk::CommonEventManager::PublishCommonEvent(commonData); return true; @@ -1315,6 +1446,75 @@ bool BundleDataMgr::GetFormsInfoByApp(const std::string &bundleName, std::vector return true; } +bool BundleDataMgr::NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) const +{ + APP_LOGI("NotifyActivityLifeStatus %{public}s, %{public}s", bundleName.c_str(), abilityName.c_str()); + if (bundleName.empty() || abilityName.empty()) { + return false; + } + std::lock_guard lock(bundleInfoMutex_); + if (bundleInfos_.empty()) { + APP_LOGI("bundleInfos_ data is empty"); + return false; + } + auto infoItem = bundleInfos_.find(bundleName); + if (infoItem == bundleInfos_.end()) { + return false; + } + APP_LOGI("NotifyActivityLifeStatus %{public}s", infoItem->first.c_str()); + auto bundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID); + if (bundleInfo == infoItem->second.end()) { + return false; + } + if (bundleInfo->second.IsDisabled()) { + APP_LOGI("app %{public}s is disabled", bundleInfo->second.GetBundleName().c_str()); + return false; + } + auto ability = bundleInfo->second.FindAbilityInfo(bundleName, abilityName); + if (!ability) { + APP_LOGE("ability:%{public}s not find", abilityName.c_str()); + return false; + } + if (ability->type != AbilityType::PAGE) { + APP_LOGE("ability:%{public}s type is not PAGE", abilityName.c_str()); + return false; + } + ModuleUsageRecord moduleUsageRecord; + moduleUsageRecord.bundleName = bundleName; + moduleUsageRecord.name = ability->moduleName; + moduleUsageRecord.abilityName = abilityName; + moduleUsageRecord.lastLaunchTime = launchTime; + moduleUsageRecord.launchedCount = 1; + return usageRecordStorage_->AddOrUpdateRecord(moduleUsageRecord, Constants::CURRENT_DEVICE_ID, 0); +} + +bool BundleDataMgr::UpdateUsageRecordOnBundleRemoved( + bool keepUsage, const int userId, const std::string &bundleName) const +{ + std::lock_guard lock(bundleInfoMutex_); + if (bundleInfos_.empty()) { + APP_LOGI("bundleInfos_ data is empty"); + return false; + } + auto infoItem = bundleInfos_.find(bundleName); + if (infoItem == bundleInfos_.end()) { + return false; + } + APP_LOGI("UpdateUsageRecordOnBundleRemoved %{public}s", infoItem->first.c_str()); + auto bundleInfo = infoItem->second.find(Constants::CURRENT_DEVICE_ID); + if (bundleInfo == infoItem->second.end()) { + return false; + } + if (bundleInfo->second.IsDisabled()) { + APP_LOGI("app %{public}s is disabled", bundleInfo->second.GetBundleName().c_str()); + return false; + } + std::vector moduleNames; + return keepUsage ? usageRecordStorage_->MarkUsageRecordRemoved(bundleInfo->second, userId) + : usageRecordStorage_->DeleteUsageRecord(bundleInfo->second, userId); +} + bool BundleDataMgr::GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) const { if (bundleName.empty()) { @@ -1343,5 +1543,164 @@ bool BundleDataMgr::GetShortcutInfos(const std::string &bundleName, std::vector< return true; } +bool BundleDataMgr::RegisterAllPermissionsChanged(const sptr &callback) +{ + if (!callback) { + APP_LOGE("callback is nullptr"); + return false; + } + std::lock_guard lock(allPermissionsChangedLock_); + std::set>::iterator it = allPermissionsCallbacks_.begin(); + while (it != allPermissionsCallbacks_.end()) { + if ((*it)->AsObject() == callback->AsObject()) { + break; + } + it++; + } + if (it == allPermissionsCallbacks_.end()) { + allPermissionsCallbacks_.emplace(callback); + } + APP_LOGD("all permissions callbacks size = %{public}zu", allPermissionsCallbacks_.size()); + return AddDeathRecipient(callback); +} + +bool BundleDataMgr::RegisterPermissionsChanged( + const std::vector &uids, const sptr &callback) +{ + if (!callback) { + APP_LOGE("callback is nullptr"); + return false; + } + std::lock_guard lock(permissionsChangedLock_); + for (int32_t uid : uids) { + std::set>::iterator it = permissionsCallbacks_[uid].begin(); + while (it != permissionsCallbacks_[uid].end()) { + if ((*it)->AsObject() == callback->AsObject()) { + break; + } + it++; + } + if (it == permissionsCallbacks_[uid].end()) { + permissionsCallbacks_[uid].emplace(callback); + } + } + APP_LOGD("specified permissions callbacks size = %{public}zu", permissionsCallbacks_.size()); + + for (const auto &item1 : permissionsCallbacks_) { + APP_LOGD("item1->first = %{public}d", item1.first); + APP_LOGD("item1->second.size() = %{public}zu", item1.second.size()); + } + return AddDeathRecipient(callback); +} + +bool BundleDataMgr::AddDeathRecipient(const sptr &callback) +{ + if (!callback) { + APP_LOGE("callback is nullptr"); + return false; + } + auto object = callback->AsObject(); + if (!object) { + APP_LOGW("callback object is nullptr"); + return false; + } + // add callback death recipient. + sptr deathRecipient = new PermissionChangedDeathRecipient(); + object->AddDeathRecipient(deathRecipient); + return true; +} + +bool BundleDataMgr::UnregisterPermissionsChanged(const sptr &callback) +{ + bool ret = false; + if (!callback) { + APP_LOGE("callback is nullptr"); + return ret; + } + { + std::lock_guard lock(allPermissionsChangedLock_); + + for (auto it = allPermissionsCallbacks_.begin(); it != allPermissionsCallbacks_.end();) { + if ((*it)->AsObject() == callback->AsObject()) { + it = allPermissionsCallbacks_.erase(it); + APP_LOGI("unregister from all permissions callbacks success!"); + ret = true; + break; + } else { + it++; + } + } + } + { + std::lock_guard lock(permissionsChangedLock_); + for (auto mapIter = permissionsCallbacks_.begin(); mapIter != permissionsCallbacks_.end();) { + for (auto it = mapIter->second.begin(); it != mapIter->second.end();) { + if ((*it)->AsObject() == callback->AsObject()) { + it = mapIter->second.erase(it); + APP_LOGI("unregister from specific permissions callbacks success!"); + APP_LOGD("mapIter->first = %{public}d", (*mapIter).first); + APP_LOGD("*mapIter.second.size() = %{public}zu", (*mapIter).second.size()); + ret = true; + } else { + it++; + } + } + if (mapIter->second.empty()) { + mapIter = permissionsCallbacks_.erase(mapIter); + } else { + mapIter++; + } + } + } + for (const auto &item1 : permissionsCallbacks_) { + APP_LOGD("item1->first = %{public}d", item1.first); + APP_LOGD("item1->second.size() = %{public}zu", item1.second.size()); + } + return ret; +} +bool BundleDataMgr::NotifyPermissionsChanged(int32_t uid) +{ + if (uid < 0) { + APP_LOGE("uid(%{private}d) is invalid", uid); + return false; + } + APP_LOGI("notify permission changed, uid = %{public}d", uid); + // for all permissions callback. + { + std::lock_guard lock(allPermissionsChangedLock_); + for (const auto &item : allPermissionsCallbacks_) { + if (!item) { + APP_LOGE("callback is nullptr"); + return false; + } + + item->OnChanged(uid); + APP_LOGD("all permissions changed callback"); + } + } + // for uid permissions callback. + { + std::lock_guard lock(permissionsChangedLock_); + APP_LOGD("specified permissions callbacks size = %{public}zu", permissionsCallbacks_.size()); + for (const auto &item1 : permissionsCallbacks_) { + APP_LOGD("item1->first = %{public}d", item1.first); + APP_LOGD("item1->second.size() = %{public}zu", item1.second.size()); + } + auto callbackItem = permissionsCallbacks_.find(uid); + if (callbackItem != permissionsCallbacks_.end()) { + auto callbacks = callbackItem->second; + for (const auto &item : callbacks) { + if (!item) { + APP_LOGE("callback is nullptr"); + return false; + } + item->OnChanged(uid); + APP_LOGD("specified permissions changed callback"); + } + } + } + return true; +} + } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/src/bundle_data_storage_database.cpp b/services/bundlemgr/src/bundle_data_storage_database.cpp index cb8f45a7d530c061d16ea9ce47ed9a636fab1e28..dcca4b3068b919ce8c9bdb32baea8239699c9d83 100644 --- a/services/bundlemgr/src/bundle_data_storage_database.cpp +++ b/services/bundlemgr/src/bundle_data_storage_database.cpp @@ -34,6 +34,7 @@ BundleDataStorageDatabase::BundleDataStorageDatabase() { APP_LOGI("instance:%{private}p is created", this); TryTwice([this] { return GetKvStore(); }); + RegisterKvStoreDeathListener(); } BundleDataStorageDatabase::~BundleDataStorageDatabase() diff --git a/services/bundlemgr/src/bundle_mgr_host_impl.cpp b/services/bundlemgr/src/bundle_mgr_host_impl.cpp index 7d9a94cda75983db6aa7f32a7cf78b7212495f03..a68c60b46b0c5566af8bd5f4734690e4605c7627 100755 --- a/services/bundlemgr/src/bundle_mgr_host_impl.cpp +++ b/services/bundlemgr/src/bundle_mgr_host_impl.cpp @@ -140,6 +140,16 @@ bool BundleMgrHostImpl::QueryAbilityInfo(const Want &want, AbilityInfo &abilityI return dataMgr->QueryAbilityInfo(want, abilityInfo); } +bool BundleMgrHostImpl::QueryAbilityInfos(const Want &want, std::vector &abilityInfos) +{ + auto dataMgr = GetDataMgrFromService(); + if (dataMgr == nullptr) { + APP_LOGE("DataMgr is nullptr"); + return false; + } + return dataMgr->QueryAbilityInfos(want, abilityInfos); +} + bool BundleMgrHostImpl::QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) { auto dataMgr = GetDataMgrFromService(); @@ -471,23 +481,52 @@ bool BundleMgrHostImpl::RequestPermissionFromUser( APP_LOGE("fail to CanRequestPermission due to params empty"); return false; } - return BundlePermissionMgr::RequestPermissionFromUser(bundleName, permissionName, userId); + bool ret = BundlePermissionMgr::RequestPermissionFromUser(bundleName, permissionName, userId); + // send Permissions Changed event + APP_LOGI("send Permissions Changed event"); + BundleInfo info; + bool ret_getInfo = GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info); + APP_LOGI("ret_getInfo = %{public}d",ret_getInfo); + if ( ret && ret_getInfo) { + Want want; + want.SetAction("PERMISSIONS_CHANGED_EVENT"); + EventFwk::CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(info.uid); + EventFwk::CommonEventManager::PublishCommonEvent(commonData); + } + return ret; } bool BundleMgrHostImpl::RegisterAllPermissionsChanged(const sptr &callback) { - return true; + auto dataMgr = GetDataMgrFromService(); + if (dataMgr == nullptr) { + APP_LOGE("DataMgr is nullptr"); + return false; + } + return dataMgr->RegisterAllPermissionsChanged(callback); } bool BundleMgrHostImpl::RegisterPermissionsChanged( const std::vector &uids, const sptr &callback) { - return true; + auto dataMgr = GetDataMgrFromService(); + if (dataMgr == nullptr) { + APP_LOGE("DataMgr is nullptr"); + return false; + } + return dataMgr->RegisterPermissionsChanged(uids,callback); } bool BundleMgrHostImpl::UnregisterPermissionsChanged(const sptr &callback) { - return true; + auto dataMgr = GetDataMgrFromService(); + if (dataMgr == nullptr) { + APP_LOGE("DataMgr is nullptr"); + return false; + } + return dataMgr->UnregisterPermissionsChanged(callback); } bool BundleMgrHostImpl::GetAllFormsInfo(std::vector &formInfos) @@ -531,6 +570,28 @@ bool BundleMgrHostImpl::GetShortcutInfos(const std::string &bundleName, std::vec return dataMgr->GetShortcutInfos(bundleName, shortcutInfos); } +bool BundleMgrHostImpl::GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) +{ + auto dataMgr = GetDataMgrFromService(); + if (dataMgr == nullptr) { + APP_LOGE("DataMgr is nullptr"); + return false; + } + return dataMgr->GetUsageRecords(number, moduleUsageRecords); +} + +bool BundleMgrHostImpl::NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) +{ + APP_LOGI("NotifyActivityLifeStatus begin"); + std::thread([this, bundleName, abilityName, launchTime]() { + auto dataMgr = GetDataMgrFromService(); + dataMgr->NotifyActivityLifeStatus(bundleName, abilityName, launchTime); + }).detach(); + APP_LOGI("NotifyActivityLifeStatus end"); + return true; +} + const std::shared_ptr BundleMgrHostImpl::GetDataMgrFromService() { return DelayedSingleton::GetInstance()->GetDataMgr(); diff --git a/services/bundlemgr/src/bundle_mgr_service.cpp b/services/bundlemgr/src/bundle_mgr_service.cpp index fd3020f0b745cc4038d2bd5b0201ee99c67fa89a..0de41228d3fe8f6e12351365356b8a2eb5ea4cd7 100644 --- a/services/bundlemgr/src/bundle_mgr_service.cpp +++ b/services/bundlemgr/src/bundle_mgr_service.cpp @@ -51,6 +51,9 @@ BundleMgrService::~BundleMgrService() if (dataMgr_) { dataMgr_.reset(); } + if (perChangeSub_) { + perChangeSub_.reset(); + } APP_LOGI("instance is destroyed"); } @@ -81,6 +84,9 @@ void BundleMgrService::OnStop() { APP_LOGI("OnStop is called"); SelfClean(); + if (perChangeSub_) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(perChangeSub_); + } } bool BundleMgrService::IsServiceReady() const @@ -143,7 +149,13 @@ bool BundleMgrService::Init() handler_->SendEvent(BMSEventHandler::BUNDLE_SCAN_START); needToScan_ = true; } - + if (!perChangeSub_) { + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent("PERMISSIONS_CHANGED_EVENT"); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + perChangeSub_ = std::make_shared(dataMgr_, subscribeInfo); + EventFwk::CommonEventManager::SubscribeCommonEvent(perChangeSub_); + } ready_ = true; APP_LOGI("init end success"); return true; diff --git a/services/bundlemgr/src/bundle_permission_mgr.cpp b/services/bundlemgr/src/bundle_permission_mgr.cpp index be095ae15f2094fbed9f6ba15f1c7d25f6ea2c86..91a84da1179df22393513352609afd6987dfe6ab 100644 --- a/services/bundlemgr/src/bundle_permission_mgr.cpp +++ b/services/bundlemgr/src/bundle_permission_mgr.cpp @@ -26,8 +26,8 @@ namespace AppExecFwk { using namespace OHOS::Security; namespace { -const std::string HOS_NORMAL_APP = "hos_normal_app"; -const std::string HOS_SYSTEM_APP = "hos_system_app"; +const std::string HOS_NORMAL_APP = "ohos_normal_app"; +const std::string HOS_SYSTEM_APP = "ohos_system_app"; // convert the Permission::PermissionDef struct to // AppExecFwk::PermissionDef struct that can be used in IPC process bool ConvertPermissionDef(const Permission::PermissionDef &permDef, PermissionDef &permissionDef) diff --git a/services/bundlemgr/src/bundle_profile.cpp b/services/bundlemgr/src/bundle_profile.cpp index b1b62331e6cf85bbb189cd972da3e5ef29a7b6e0..1f53df16c4e44d21b56a543c6c2798e029306fab 100644 --- a/services/bundlemgr/src/bundle_profile.cpp +++ b/services/bundlemgr/src/bundle_profile.cpp @@ -149,6 +149,8 @@ struct Forms { std::string scheduledUpateTime = "0:0"; int32_t updateDuration = 0; std::string deepLink; + std::string formConfigAbility; + bool formVisibleNotify = false; std::string jsComponentName; FormsMetaData metaData; }; @@ -174,7 +176,7 @@ struct CustomizeData { struct MetaData { std::vector parameters; std::vector results; - std::vector customizeData; + std::vector customizeData; }; struct UriPermission { @@ -201,6 +203,8 @@ struct Ability { std::vector deviceCapability; MetaData metaData; std::string type; + std::string srcPath; + std::string srcLanguage = "js"; bool formEnabled = false; Form form; std::string orientation = "unspecified"; @@ -256,6 +260,7 @@ struct Module { std::string package; std::string name; std::string description; + int32_t descriptionId = 0; std::string colorMode = "auto"; std::vector supportedModes; std::vector reqCapabilities; @@ -789,7 +794,7 @@ void from_json(const nlohmann::json &jsonObject, MetaData &metaData) { // these are not required fields. const auto &jsonObjectEnd = jsonObject.end(); - GetValueIfFindKey>(jsonObject, + GetValueIfFindKey>(jsonObject, jsonObjectEnd, BUNDLE_MODULE_META_KEY_CUSTOMIZE_DATA, metaData.customizeData, @@ -976,6 +981,22 @@ void from_json(const nlohmann::json &jsonObject, Forms &forms) false, parseResult, ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + BUNDLE_MODULE_PROFILE_FORMS_FORM_CONFIG_ABILITY, + forms.formConfigAbility, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + BUNDLE_MODULE_PROFILE_FORMS_FORM_VISIBLE_NOTIFY, + forms.formVisibleNotify, + JsonType::BOOLEAN, + false, + parseResult, + ArrayType::NOT_ARRAY); GetValueIfFindKey(jsonObject, jsonObjectEnd, BUNDLE_MODULE_PROFILE_KEY_META_DATA, @@ -1037,6 +1058,22 @@ void from_json(const nlohmann::json &jsonObject, Ability &ability) parseResult, ArrayType::NOT_ARRAY); // these are not required fields. + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + PROFILE_KEY_SRCPATH, + ability.srcPath, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + PROFILE_KEY_SRCLANGUAGE, + ability.srcLanguage, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); GetValueIfFindKey(jsonObject, jsonObjectEnd, PROFILE_KEY_DESCRIPTION, @@ -1509,6 +1546,14 @@ void from_json(const nlohmann::json &jsonObject, Module &module) false, parseResult, ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + PROFILE_KEY_DESCRIPTION_ID, + module.descriptionId, + JsonType::NUMBER, + false, + parseResult, + ArrayType::NOT_ARRAY); GetValueIfFindKey>(jsonObject, jsonObjectEnd, BUNDLE_MODULE_PROFILE_KEY_SUPPORTED_MODES, @@ -1686,8 +1731,7 @@ bool CheckModuleInfosIsValid(ProfileReader::ConfigJson &configJson) } return true; } - -uint32_t GetFormEntity(const std::vector& formEntity) +uint32_t GetFormEntity(const std::vector &formEntity) { if (ProfileReader::formEntityMap.empty()) { ProfileReader::formEntityMap.insert({ProfileReader::KEY_HOME_SCREEN, ProfileReader::VALUE_HOME_SCREEN}); @@ -1695,7 +1739,7 @@ uint32_t GetFormEntity(const std::vector& formEntity) } uint32_t formEntityInBinary = 0; - for (const auto& item : formEntity) { + for (const auto &item : formEntity) { if (ProfileReader::formEntityMap.find(item) != ProfileReader::formEntityMap.end()) { formEntityInBinary |= ProfileReader::formEntityMap[item]; } @@ -1708,7 +1752,8 @@ bool ConvertFormInfo(FormInfo &forminfos, const ProfileReader::Forms &form) forminfos.name = form.name; forminfos.description = form.description; forminfos.descriptionId = form.descriptionId; - forminfos.formConfigAbility = form.deepLink; + forminfos.formConfigAbility = form.formConfigAbility; + forminfos.formVisibleNotify = form.formVisibleNotify; forminfos.deepLink = form.deepLink; forminfos.defaultFlag = form.isDefault; auto type = std::find_if(std::begin(ProfileReader::formTypeMap), @@ -1727,13 +1772,13 @@ bool ConvertFormInfo(FormInfo &forminfos, const ProfileReader::Forms &form) forminfos.scheduledUpateTime = form.scheduledUpateTime; forminfos.updateDuration = form.updateDuration; forminfos.jsComponentName = form.jsComponentName; - for (auto data : form.metaData.customizeData) { + for (auto &data : form.metaData.customizeData) { FormCustomizeData customizeData; customizeData.name = data.name; customizeData.value = data.value; forminfos.customizeDatas.emplace_back(customizeData); } - for (const auto dimensions : form.supportDimensions) { + for (const auto &dimensions : form.supportDimensions) { auto dimension = std::find_if(std::begin(ProfileReader::dimensionMap), std::end(ProfileReader::dimensionMap), [&dimensions](const auto &item) { return item.first == dimensions; }); @@ -1801,21 +1846,21 @@ bool TransformToInfo(const ProfileReader::ConfigJson &configJson, BundleInfo &bu void GetMetaData(MetaData &metaData, const ProfileReader::MetaData &profileMetaData) { - for (const auto& item : profileMetaData.parameters) { + for (const auto &item : profileMetaData.parameters) { Parameters parameter; parameter.description = item.description; parameter.name = item.name; parameter.type = item.type; metaData.parameters.emplace_back(parameter); } - for (const auto& item : profileMetaData.results) { + for (const auto &item : profileMetaData.results) { Results result; result.description = item.description; result.name = item.name; result.type = item.type; metaData.results.emplace_back(result); } - for (const auto& item : profileMetaData.customizeData) { + for (const auto &item : profileMetaData.customizeData) { CustomizeData customizeData; customizeData.name = item.name; customizeData.extra = item.extra; @@ -1829,6 +1874,7 @@ bool TransformToInfo(const ProfileReader::ConfigJson &configJson, InnerModuleInf innerModuleInfo.modulePackage = configJson.module.package; innerModuleInfo.moduleName = configJson.module.distro.moduleName; innerModuleInfo.description = configJson.module.description; + innerModuleInfo.descriptionId = configJson.module.descriptionId; auto colorModeInfo = std::find_if(std::begin(ProfileReader::moduleColorMode), std::end(ProfileReader::moduleColorMode), [&configJson](const auto &item) { return item.first == configJson.module.colorMode; }); @@ -1847,11 +1893,19 @@ bool TransformToInfo( const ProfileReader::ConfigJson &configJson, const ProfileReader::Ability &ability, AbilityInfo &abilityInfo) { abilityInfo.name = ability.name; + if (ability.srcLanguage != "c++" && ability.name.substr(0, 1) == ".") { + abilityInfo.name = configJson.module.package + ability.name; + } abilityInfo.label = ability.label; abilityInfo.description = ability.description; abilityInfo.iconPath = ability.icon; + abilityInfo.labelId = ability.labelId; + abilityInfo.descriptionId = ability.descriptionId; + abilityInfo.iconId = ability.iconId; abilityInfo.visible = ability.visible; abilityInfo.kind = ability.type; + abilityInfo.srcPath = ability.srcPath; + abilityInfo.srcLanguage = ability.srcLanguage; auto iterType = std::find_if(std::begin(ProfileReader::ABILITY_TYPE_MAP), std::end(ProfileReader::ABILITY_TYPE_MAP), [&ability](const auto &item) { return item.first == ability.type; }); @@ -1882,6 +1936,10 @@ bool TransformToInfo( abilityInfo.theme = ability.theme; abilityInfo.deviceTypes = configJson.module.deviceType; abilityInfo.deviceCapabilities = ability.deviceCapability; + if (iterType->second == AbilityType::DATA && + ability.uri.find(Constants::DATA_ABILITY_URI_PREFIX) == std::string::npos) { + return false; + } abilityInfo.uri = ability.uri; abilityInfo.package = configJson.module.package; abilityInfo.bundleName = configJson.app.bundleName; @@ -1889,8 +1947,10 @@ bool TransformToInfo( abilityInfo.applicationName = configJson.app.bundleName; abilityInfo.targetAbility = ability.targetAbility; abilityInfo.enabled = true; + abilityInfo.supportPipMode = ability.supportPipMode; abilityInfo.readPermission = ability.readPermission; abilityInfo.writePermission = ability.writePermission; + abilityInfo.configChanges = ability.configChanges; abilityInfo.formEntity = GetFormEntity(ability.form.formEntity); abilityInfo.minFormHeight = ability.form.minHeight; abilityInfo.defaultFormHeight = ability.form.defaultHeight; @@ -1951,6 +2011,9 @@ bool TransformToInfo(ProfileReader::ConfigJson &configJson, InnerBundleInfo &inn FormInfo formInfo; ConvertFormInfo(formInfo, form); formInfo.abilityName = ability.name; + if (ability.srcLanguage != "c++" && ability.name.substr(0, 1) == ".") { + formInfo.abilityName = configJson.module.package + ability.name; + } formInfo.bundleName = configJson.app.bundleName; formInfo.moduleName = configJson.module.distro.moduleName; formInfo.package = configJson.module.package; @@ -1967,6 +2030,9 @@ bool TransformToInfo(ProfileReader::ConfigJson &configJson, InnerBundleInfo &inn (find == false)) { innerBundleInfo.SetMainAbility(keyName); innerBundleInfo.SetMainAbilityName(ability.name); + if (ability.srcLanguage != "c++" && ability.name.substr(0, 1) == ".") { + innerBundleInfo.SetMainAbilityName(configJson.module.package + ability.name); + } // if there is main ability, it's label will be the application's label applicationInfo.label = ability.label; applicationInfo.labelId = ability.labelId; @@ -1974,6 +2040,10 @@ bool TransformToInfo(ProfileReader::ConfigJson &configJson, InnerBundleInfo &inn applicationInfo.iconId = ability.iconId; applicationInfo.description = ability.description; applicationInfo.descriptionId = ability.descriptionId; + if (innerModuleInfo.label.empty()) { + innerModuleInfo.label = ability.label; + innerModuleInfo.labelId = ability.labelId; + } find = true; } if (std::find(skill.entities.begin(), skill.entities.end(), Constants::FLAG_HOME_INTENT_FROM_SYSTEM) != diff --git a/services/bundlemgr/src/inner_bundle_info.cpp b/services/bundlemgr/src/inner_bundle_info.cpp index 8d4251b3c334ca757f0722595d42fb6a1539d328..5e6bd27c983e003a1b7329b67f26637f19e349e1 100644 --- a/services/bundlemgr/src/inner_bundle_info.cpp +++ b/services/bundlemgr/src/inner_bundle_info.cpp @@ -41,6 +41,10 @@ const std::string MODULE_PACKAGE = "modulePackage"; const std::string MODULE_PATH = "modulePath"; const std::string MODULE_NAME = "moduleName"; const std::string MODULE_DESCRIPTION = "description"; +const std::string MODULE_DESCRIPTION_ID = "descriptionId"; +const std::string MODULE_LABEL = "label"; +const std::string MODULE_LABEL_ID = "labelId"; +const std::string MODULE_DESCRIPTION_INSTALLATION_FREE = "installationFree"; const std::string MODULE_IS_ENTRY = "isEntry"; const std::string MODULE_METADATA = "metaData"; const std::string MODULE_COLOR_MODE = "colorMode"; @@ -67,14 +71,13 @@ InnerBundleInfo::~InnerBundleInfo() APP_LOGD("inner bundle info instance is destroyed"); } - - void to_json(nlohmann::json &jsonObject, const Distro &distro) { jsonObject = nlohmann::json{ {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DELIVERY_WITH_INSTALL, distro.deliveryWithInstall}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_NAME, distro.moduleName}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_TYPE, distro.moduleType} + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_TYPE, distro.moduleType}, + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_INSTALLATION_FREE, distro.installationFree} }; } @@ -121,6 +124,10 @@ void to_json(nlohmann::json &jsonObject, const InnerModuleInfo &info) {MODULE_COLOR_MODE, info.colorMode}, {MODULE_DISTRO, info.distro}, {MODULE_DESCRIPTION, info.description}, + {MODULE_DESCRIPTION_ID, info.descriptionId}, + {MODULE_LABEL, info.label}, + {MODULE_LABEL_ID, info.labelId}, + {MODULE_DESCRIPTION_INSTALLATION_FREE, info.installationFree}, {MODULE_REQ_CAPABILITIES, info.reqCapabilities}, {MODULE_REQ_PERMS, info.reqPermissions}, {MODULE_DEF_PERMS, info.defPermissions}, @@ -255,6 +262,38 @@ void from_json(const nlohmann::json &jsonObject, InnerModuleInfo &info) false, ProfileReader::parseResult, ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + MODULE_DESCRIPTION_ID, + info.descriptionId, + JsonType::NUMBER, + false, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + MODULE_LABEL, + info.label, + JsonType::STRING, + false, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + MODULE_LABEL_ID, + info.labelId, + JsonType::NUMBER, + false, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + MODULE_DESCRIPTION_INSTALLATION_FREE, + info.installationFree, + JsonType::BOOLEAN, + false, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); GetValueIfFindKey>(jsonObject, jsonObjectEnd, MODULE_REQ_CAPABILITIES, @@ -374,8 +413,6 @@ void from_json(const nlohmann::json &jsonObject, Skill &skill) ArrayType::OBJECT); } - - void from_json(const nlohmann::json &jsonObject, Distro &distro) { const auto &jsonObjectEnd = jsonObject.end(); @@ -403,6 +440,15 @@ void from_json(const nlohmann::json &jsonObject, Distro &distro) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); + // mustFlag decide by distro.moduleType + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_INSTALLATION_FREE, + distro.installationFree, + JsonType::BOOLEAN, + false, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); } void from_json(const nlohmann::json &jsonObject, UsedScene &usedScene) @@ -723,6 +769,26 @@ std::optional InnerBundleInfo::FindAbilityInfo( return std::nullopt; } +std::optional> InnerBundleInfo::FindAbilityInfos(const std::string &bundleName) const +{ + std::vector abilitys; + + if (bundleName.empty()) { + return std::nullopt; + } + + for (const auto &ability : baseAbilityInfos_) { + if ((ability.second.bundleName == bundleName)) { + abilitys.emplace_back(ability.second); + } + } + if (!abilitys.empty()) { + return abilitys; + } + + return std::nullopt; +} + bool InnerBundleInfo::AddModuleInfo(const InnerBundleInfo &newInfo) { if (newInfo.currentPackage_.empty()) { @@ -941,5 +1007,22 @@ void InnerBundleInfo::GetShortcutInfos(std::vector &shortcutInfos) } } +std::optional InnerBundleInfo::GetInnerModuleInfoByModuleName(const std::string &moduleName) const +{ + for (const auto &innerModuleInfo : innerModuleInfos_) { + if (innerModuleInfo.second.moduleName == moduleName) { + return innerModuleInfo.second; + } + } + return std::nullopt; +} + +void InnerBundleInfo::GetModuleNames(std::vector &moduleNames) const +{ + for (const auto &innerModuleInfo : innerModuleInfos_) { + moduleNames.emplace_back(innerModuleInfo.second.moduleName); + } +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/services/bundlemgr/src/module_usage_data_storage.cpp b/services/bundlemgr/src/module_usage_data_storage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5044b12a8f23c9e0e55051b3471ddbddd2efdedf --- /dev/null +++ b/services/bundlemgr/src/module_usage_data_storage.cpp @@ -0,0 +1,383 @@ +/* + * Copyright (c) 2021 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_usage_data_storage.h" + +#include +#include +#include "datetime_ex.h" +#include "permission/permission_kit.h" +#include "string_ex.h" + +#include "app_log_wrapper.h" +#include "bundle_util.h" +#include "kvstore_death_recipient_callback.h" +#include "nlohmann/json.hpp" + +using namespace OHOS::DistributedKv; + +namespace OHOS { +namespace AppExecFwk { +namespace { + +const int32_t MAX_TIMES = 6000; // tem min +const int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms +const std::string POUND_KEY_SEPARATOR = "#"; +const std::string SCHEMA_DEFINE = "{\"SCHEMA_VERSION\":\"1.0\"," + "\"SCHEMA_MODE\":\"COMPATIBLE\"," + "\"SCHEMA_SKIPSIZE\":0," + "\"SCHEMA_DEFINE\":{" + "\"launchedCount\":\"INTEGER, NOT NULL\"," + "\"lastLaunchTime\":\"LONG, NOT NULL\"," + "\"isRemoved\":\"BOOL, NOT NULL\"" + "}," + "\"SCHEMA_INDEXES\":[\"$.lastLaunchTime\"]}"; +} // namespace + +ModuleUsageRecordStorage::ModuleUsageRecordStorage() +{ + APP_LOGI("usage instance is created"); + TryTwice([this] { return GetKvStore(); }); +} + +ModuleUsageRecordStorage::~ModuleUsageRecordStorage() +{ + APP_LOGI("usage instance is destroyed"); + dataManager_.CloseKvStore(appId_, std::move(kvStorePtr_)); +} + +void ModuleUsageRecordStorage::RegisterKvStoreDeathListener() +{} + +bool ModuleUsageRecordStorage::ParseKey(const std::string &key, ModuleUsageRecord &record) const +{ + std::vector splitKeys; + SplitStr(key, POUND_KEY_SEPARATOR, splitKeys); + if (splitKeys.size() != DATABASE_KEY_INDEX_MAX_LENGTH) { + APP_LOGE("error key, parsed failed!"); + return false; + } + + record.bundleName = (splitKeys[DATABASE_KEY_INDEX_BUNDLE_NAME]); + record.name = (splitKeys[DATABASE_KEY_INDEX_MODULE_NAME]); + APP_LOGD( + "parseKey::bundleName = %{public}s, moduleName = %{public}s", record.bundleName.c_str(), record.name.c_str()); + return true; +} + +void ModuleUsageRecordStorage::AbilityRecordToKey(const std::string &userId, const std::string &deviceId, + const std::string &bundleName, const std::string &moduleName, std::string &key) const +{ + // deviceId_bundleName_moduleName + key.append(userId); + key.append(POUND_KEY_SEPARATOR); + key.append(deviceId); + key.append(POUND_KEY_SEPARATOR); + key.append(bundleName); + key.append(POUND_KEY_SEPARATOR); + key.append(moduleName); + APP_LOGD("userId = %{public}s, bundleName = %{public}s, moduleName = %{public}s", + userId.c_str(), + bundleName.c_str(), + moduleName.c_str()); +} + +void ModuleUsageRecordStorage::UpdateUsageRecord(const std::string &jsonString, ModuleUsageRecord &data) +{ + nlohmann::json jsonObject; + jsonObject = nlohmann::json::parse(jsonString); + if (jsonObject.is_discarded()) { + APP_LOGE("failed to parse existing usage record: %{private}s.", jsonString.c_str()); + return; + } + uint32_t launchedCount = jsonObject.at(UsageRecordKey::LAUNCHED_COUNT).get(); + data.launchedCount = launchedCount + 1; + APP_LOGD("launchedCount = %{public}d", data.launchedCount); + return; +} + +bool ModuleUsageRecordStorage::AddOrUpdateRecord(ModuleUsageRecord &data, const std::string &deviceId, int32_t userId) +{ + APP_LOGI("add usage record data %{public}s", data.bundleName.c_str()); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return false; + } + } + Status status; + bool isExist = false; + { + std::string keyOfData; + AbilityRecordToKey(std::to_string(userId), deviceId, data.bundleName, data.name, keyOfData); + Key key(keyOfData); + Value oldValue; + std::lock_guard lock(kvStorePtrMutex_); + status = kvStorePtr_->Get(key, oldValue); + if (status == Status::SUCCESS) { + APP_LOGD("get old value %{public}s", oldValue.ToString().c_str()); + // already isExist, update + UpdateUsageRecord(oldValue.ToString(), data); + isExist = true; + } + if (status == Status::KEY_NOT_FOUND || isExist) { + Value value(data.ToString()); + APP_LOGD("add to DB::value %{public}s", value.ToString().c_str()); + status = kvStorePtr_->Put(key, value); + APP_LOGW("add result = %{public}d", status); + if (status == Status::IPC_ERROR) { + status = kvStorePtr_->Put(key, value); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + } + } + + if (status != Status::SUCCESS) { + APP_LOGE("put value to kvStore error: %{public}d", status); + return false; + } + + APP_LOGD("update success"); + return true; +} + +bool ModuleUsageRecordStorage::DeleteRecordByKeys(const std::string &bundleName, std::vector &keys) +{ + if (keys.size() == 0) { + APP_LOGE("delete error: empty key"); + return false; + } + Status status; + { + std::lock_guard lock(kvStorePtrMutex_); + status = kvStorePtr_->DeleteBatch(keys); + if (status == Status::IPC_ERROR) { + status = kvStorePtr_->DeleteBatch(keys); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + } + + if (status != Status::SUCCESS) { + APP_LOGE("delete keys error: %{public}d", status); + return false; + } + APP_LOGD("delete success"); + return true; +} + +bool ModuleUsageRecordStorage::DeleteUsageRecord(const InnerBundleInfo &data, int32_t userId) +{ + APP_LOGD("delete usage data"); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return false; + } + } + + std::vector keys; + InnerBundleInfoToKeys(data, userId, keys); + APP_LOGD("delete key %{public}zu", keys.size()); + return DeleteRecordByKeys(data.GetBundleName(), keys); +} + +bool ModuleUsageRecordStorage::MarkUsageRecordRemoved(const InnerBundleInfo &data, int32_t userId) +{ + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return false; + } + } + ModuleUsageRecord record; + Value value; + std::string jsonString; + std::vector keys; + InnerBundleInfoToKeys(data, userId, keys); + { + std::lock_guard lock(kvStorePtrMutex_); + for (const Key &key : keys) { + Status status = kvStorePtr_->Get(key, value); + if (status != Status::SUCCESS) { + APP_LOGD("database query by key error, result = %{public}d", status); + return false; + } + if (!record.FromJsonString(value.ToString())) { + APP_LOGW("database parse entry failed"); + return false; + } + if (!record.removed) { + record.removed = true; + jsonString = record.ToString(); + APP_LOGD("new value %{public}s", jsonString.c_str()); + value = jsonString; + status = kvStorePtr_->Put(key, value); + APP_LOGI("value update result: %{public}d", status); + } + } + } + return true; +} + +void ModuleUsageRecordStorage::InnerBundleInfoToKeys( + const InnerBundleInfo &data, int32_t userId, std::vector &keys) const +{ + std::vector mouduleNames; + data.GetModuleNames(mouduleNames); + const std::string &bundleName = data.GetBundleName(); + for (const auto &moduleName : mouduleNames) { + FillDataStorageKeys(std::to_string(userId), bundleName, moduleName, keys); + } +} + +void ModuleUsageRecordStorage::FillDataStorageKeys(const std::string &userId, const std::string &bundleName, + const std::string &moduleName, std::vector &keys) const +{ + std::string keyOfData; + AbilityRecordToKey(userId, Constants::CURRENT_DEVICE_ID, bundleName, moduleName, keyOfData); + Key key(keyOfData); + keys.push_back(key); +} + +void ModuleUsageRecordStorage::SaveEntries( + const std::vector &allEntries, std::vector &records) const +{ + APP_LOGD("SaveEntries %{public}zu", allEntries.size()); + for (const auto &item : allEntries) { + APP_LOGD("SaveEntries %{public}s", item.value.ToString().c_str()); + ModuleUsageRecord record; + if (!record.FromJsonString(item.value.ToString())) { + APP_LOGE("error entry: %{private}s", item.value.ToString().c_str()); + continue; + } + + if (!ParseKey(item.key.ToString(), record)) { + APP_LOGE("error key"); + continue; + } + records.emplace_back(record); + } +} + +bool ModuleUsageRecordStorage::QueryRecordByNum(int32_t maxNum, std::vector &records, int32_t userId) +{ + APP_LOGI("query record by num %{public}d userId %{public}d", maxNum, userId); + DataQuery query; + query.KeyPrefix(std::to_string(userId) + POUND_KEY_SEPARATOR + Constants::CURRENT_DEVICE_ID + POUND_KEY_SEPARATOR); + query.OrderByDesc(UsageRecordKey::SCHEMA_LAST_LAUNCH_TIME); + query.Limit(maxNum, 0); + std::vector allEntries; + bool queryResult = QueryRecordByCondition(query, allEntries); + if (!queryResult || static_cast(allEntries.size()) > maxNum) { + APP_LOGE("query record error"); + return queryResult; + } + APP_LOGD("query record success"); + SaveEntries(allEntries, records); + return true; +} + +bool ModuleUsageRecordStorage::QueryRecordByCondition(DataQuery &query, std::vector &records) +{ + Status status; + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return false; + } + } + + status = kvStorePtr_->GetEntriesWithQuery(query, records); + APP_LOGI("query record by condition %{public}d", status); + if (status == Status::IPC_ERROR) { + status = kvStorePtr_->GetEntriesWithQuery(query, records); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + + if (status != Status::SUCCESS) { + APP_LOGE("query key error: %{public}d", status); + return false; + } + return true; +} + +Status ModuleUsageRecordStorage::GetKvStore() +{ + Status status; + Options options = { + .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION}; + + options.schema = SCHEMA_DEFINE; + dataManager_.GetSingleKvStore( + options, appId_, storeId_, [this, &status](Status paramStatus, std::unique_ptr singleKvStore) { + status = paramStatus; + if (status != Status::SUCCESS) { + APP_LOGE("usage get kvStore error: %{public}d", status); + return; + } + { + kvStorePtr_ = std::move(singleKvStore); + } + APP_LOGI("usage get kvStore success"); + }); + + return status; +} + +void ModuleUsageRecordStorage::TryTwice(const std::function &func) const +{ + Status status = func(); + if (status == Status::IPC_ERROR) { + status = func(); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } +} + +bool ModuleUsageRecordStorage::CheckKvStore() +{ + if (kvStorePtr_ != nullptr) { + return true; + } + int32_t tryTimes = MAX_TIMES; + while (tryTimes > 0) { + Status status = GetKvStore(); + if (status == Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + APP_LOGD("usage CheckKvStore, Times: %{public}d", tryTimes); + usleep(SLEEP_INTERVAL); + tryTimes--; + } + return kvStorePtr_ != nullptr; +} + +bool ModuleUsageRecordStorage::ResetKvStore() +{ + std::lock_guard lock(kvStorePtrMutex_); + kvStorePtr_ = nullptr; + Status status = GetKvStore(); + if (status == Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + APP_LOGW("usage reset failed"); + return false; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/bundlemgr/src/permission_changed_death_recipient.cpp b/services/bundlemgr/src/permission_changed_death_recipient.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47eafa62275774042e5c7b540b77a9f4fcb76c12 --- /dev/null +++ b/services/bundlemgr/src/permission_changed_death_recipient.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 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 "permission_changed_death_recipient.h" + +#include "iremote_broker.h" + +#include "app_log_wrapper.h" +#include "bundle_mgr_service.h" + +namespace OHOS { +namespace AppExecFwk { + +void PermissionChangedDeathRecipient::OnRemoteDied(const wptr& object) +{ + APP_LOGI("permission changed callback died, remove the callback"); + sptr callback = iface_cast(object.promote()); + DelayedSingleton::GetInstance()->GetDataMgr()->UnregisterPermissionsChanged(callback); +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h index e702d4d634b62467d9c021486c970db44062edfd..df955fb47263a5e3626369d68303e92d2459305a 100644 --- a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h +++ b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h @@ -190,6 +190,11 @@ public: return 0; } + int UpdateConfiguration(const DummyConfiguration &config) override + { + return 0; + } + virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override { @@ -239,6 +244,43 @@ public: { return 0; } + int MoveMissionToFloatingStack(const MissionOption &missionOption) override + { + return 0; + } + int MoveMissionToSplitScreenStack(const MissionOption &missionOption) override + { + return 0; + } + int MinimizeMultiWindow(int missionId) override + { + return 0; + } + int MaximizeMultiWindow(int missionId) override + { + return 0; + } + int GetFloatingMissions(std::vector &list) override + { + return 0; + } + int CloseMultiWindow(int missionId) override + { + return 0; + } + int SetMissionStackSetting(const StackSetting &stackSetting) override + { + return 0; + } + int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = 0) override + { + return 0; + } + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) override + { + return 0; + } }; } // namespace AppExecFwk diff --git a/services/bundlemgr/test/mock/include/mock_bundle_status.h b/services/bundlemgr/test/mock/include/mock_bundle_status.h index c68bdd27c71987d4e941cfe8341a2b65ebb3a6ca..fb7057b08b99e9fd06bc48b6587bd7d76adc7d86 100644 --- a/services/bundlemgr/test/mock/include/mock_bundle_status.h +++ b/services/bundlemgr/test/mock/include/mock_bundle_status.h @@ -32,6 +32,9 @@ public: virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) override; + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override {}; + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override {}; + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override {}; virtual sptr AsObject() override; int32_t GetResultCode(); diff --git a/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_database_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_database_test.cpp index c526bc7237bf87c2fe1f86cfeaeed367a3c3bad2..934053a40a21ed353446605022a0561b6a6c4a69 100644 --- a/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_database_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_database_test.cpp @@ -71,32 +71,35 @@ protected: "enabled": true, "readPermission": "readPermission", "writePermission": "writePermission", - "form": { - "formEntity": ["homeScreen", "searchbox"], - "minHeight": 0, - "defaultHeight": 100, - "minWidth": 0, - "defaultWidth": 200 - }, + "configChanges": [ + "locale" + ], + "formEnabled": true, + "formEntity": 1, + "minFormHeight": 0, + "defaultFormHeight": 100, + "minFormWidth": 0, + "defaultFormWidth": 200, "metaData": { "customizeData": [{ - ? "name" : "string", - ? "value" : "string", - ? "extra" : "$string:customizeData_description" + "name" : "string", + "value" : "string", + "extra" : "$string:customizeData_description" }], "parameters": [{ "name" : "string", - ? "type" : "Float", - ? "description" : "$string:parameters_description" + "type" : "Float", + "description" : "$string:parameters_description" }], "results": [{ - ? "name" : "string", - ? "type" : "Float", - ? "description" : "$string:results_description" + "name" : "string", + "type" : "Float", + "description" : "$string:results_description" }] }, "isLauncherAbility": true, "isNativeAbility": false, + "supportPipMode" : false, "kind": "page", "label": "Launcher", "launchMode": 0, @@ -111,7 +114,10 @@ protected: "targetAbility": "", "type": 1, "uri": "", - "visible": false + "visible": false, + "labelId": 1, + "descriptionId": 1, + "iconId": 1 } }, "baseApplicationInfo": { @@ -290,6 +296,25 @@ protected: } ] }, + "shortcutInfos": { + "com.example.myapplication1com.example.myapplication.h1id": { + "bundleName": "com.example.myapplication1", + "disableMessage": "", + "hostAbility": "", + "icon": "$string:mainability_description", + "id": "id", + "intents": [ + { + "targetBundle": "com.example.myapplication1", + "targetClass": "com.example.myapplication.MainAbility" + } + ], + "isEnables": false, + "isHomeShortcut": false, + "isStatic": false, + "label": "$string:mainability_description" + } + }, "uid": 10000, "userId_": 0 } @@ -347,14 +372,14 @@ void BmsBundleDataStorageDatabaseTest::CheckInvalidPropDeserialize( throwError = true; } - ASSERT_TRUE(throwError); + EXPECT_TRUE(throwError); if (!throwError) { GTEST_LOG_(ERROR) << "not catch any type_error"; } innerBundleInfoJson["baseBundleInfo"] = bundleInfoJson; InnerBundleInfo fromJsonInfo; - ASSERT_FALSE(fromJsonInfo.FromJson(innerBundleInfoJson)); + EXPECT_FALSE(fromJsonInfo.FromJson(innerBundleInfoJson)); } void BmsBundleDataStorageDatabaseTest::SetUpTestCase() @@ -383,7 +408,7 @@ HWTEST_F(BmsBundleDataStorageDatabaseTest, BundleInfoJsonSerializer_0100, Functi // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -426,7 +451,7 @@ HWTEST_F(BmsBundleDataStorageDatabaseTest, AbilityInfoJsonSerializer_0100, Funct AbilityInfo fromJsonInfo = sourceInfoJson; // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -479,7 +504,7 @@ HWTEST_F(BmsBundleDataStorageDatabaseTest, ApplicationInfoJsonSerializer_0100, F // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -521,7 +546,7 @@ HWTEST_F(BmsBundleDataStorageDatabaseTest, ModuleInfoJsonSerializer_0100, Functi // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -533,5 +558,5 @@ HWTEST_F(BmsBundleDataStorageDatabaseTest, ModuleInfoJsonSerializer_0100, Functi HWTEST_F(BmsBundleDataStorageDatabaseTest, SaveData_0100, Function | SmallTest | Level0) { InnerBundleInfo innerBundleInfo; - ASSERT_EQ(innerBundleInfo.FromJson(innerBundleInfoJson_), OHOS::ERR_OK); + EXPECT_EQ(innerBundleInfo.FromJson(innerBundleInfoJson_), OHOS::ERR_OK); } \ No newline at end of file diff --git a/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_test.cpp index cd8daa5ba9bcc1b588fd53da737efaaff5de6929..eaad3caca1ef7c7cec95da84ec068055373da898 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_data_storage_test/bms_bundle_data_storage_test.cpp @@ -260,30 +260,30 @@ BmsBundleDataStorageTest::~BmsBundleDataStorageTest() void BmsBundleDataStorageTest::CheckBundleSaved(const InnerBundleInfo &innerBundleInfo) const { BundleDataStorage bundleDataStorage; - ASSERT_TRUE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); + EXPECT_TRUE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); std::map> bundleData; - ASSERT_TRUE(bundleDataStorage.LoadAllData(bundleData)); + EXPECT_TRUE(bundleDataStorage.LoadAllData(bundleData)); // search allDeviceInfos by bundle name std::string bundleName = innerBundleInfo.GetBundleName(); auto bundleDataIter = bundleData.find(bundleName); - ASSERT_TRUE(bundleDataIter != bundleData.end()); + EXPECT_TRUE(bundleDataIter != bundleData.end()); // search InnerBundleInfo by device id auto allDeviceInfos = bundleDataIter->second; auto devicesInfosIter = allDeviceInfos.find(deviceId_); - ASSERT_TRUE(devicesInfosIter != allDeviceInfos.end()); + EXPECT_TRUE(devicesInfosIter != allDeviceInfos.end()); InnerBundleInfo afterLoadInfo = devicesInfosIter->second; - ASSERT_TRUE(innerBundleInfo.ToString() == afterLoadInfo.ToString()); + EXPECT_TRUE(innerBundleInfo.ToString() == afterLoadInfo.ToString()); } void BmsBundleDataStorageTest::CheckBundleDeleted(const InnerBundleInfo &innerBundleInfo) const { BundleDataStorage bundleDataStorage; - ASSERT_TRUE(bundleDataStorage.DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); + EXPECT_TRUE(bundleDataStorage.DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); std::map> bundleDates; - ASSERT_TRUE(bundleDataStorage.LoadAllData(bundleDates)); + EXPECT_TRUE(bundleDataStorage.LoadAllData(bundleDates)); } void BmsBundleDataStorageTest::CheckInvalidPropDeserialize(const nlohmann::json infoJson, const InfoType infoType) const @@ -317,14 +317,14 @@ void BmsBundleDataStorageTest::CheckInvalidPropDeserialize(const nlohmann::json throwError = true; } - ASSERT_TRUE(throwError); + EXPECT_TRUE(throwError); if (!throwError) { GTEST_LOG_(ERROR) << "not catch any type_error"; } innerBundleInfoJson["baseBundleInfo"] = bundleInfoJson; InnerBundleInfo fromJsonInfo; - ASSERT_FALSE(fromJsonInfo.FromJson(innerBundleInfoJson)); + EXPECT_FALSE(fromJsonInfo.FromJson(innerBundleInfoJson)); } void BmsBundleDataStorageTest::SetUpTestCase() @@ -366,7 +366,7 @@ HWTEST_F(BmsBundleDataStorageTest, BundleInfoJsonSerializer_0100, Function | Sma // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -409,7 +409,7 @@ HWTEST_F(BmsBundleDataStorageTest, AbilityInfoJsonSerializer_0100, Function | Sm AbilityInfo fromJsonInfo = sourceInfoJson; // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -462,7 +462,7 @@ HWTEST_F(BmsBundleDataStorageTest, ApplicationInfoJsonSerializer_0100, Function // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -504,7 +504,7 @@ HWTEST_F(BmsBundleDataStorageTest, ModuleInfoJsonSerializer_0100, Function | Sma // serialize fromJsonInfo to json nlohmann::json toJsonObject = fromJsonInfo; - ASSERT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); + EXPECT_TRUE(toJsonObject.dump() == sourceInfoJson.dump()); } /** @@ -571,8 +571,8 @@ HWTEST_F(BmsBundleDataStorageTest, SaveData_0400, Function | SmallTest | Level1) { nlohmann::json sourceInfoJson = innerBundleInfoJson_; InnerBundleInfo fromJsonInfo; - ASSERT_EQ(fromJsonInfo.FromJson(innerBundleInfoJson_), 0); - ASSERT_TRUE(fromJsonInfo.ToString() == sourceInfoJson.dump()); + EXPECT_EQ(fromJsonInfo.FromJson(innerBundleInfoJson_), 0); + EXPECT_TRUE(fromJsonInfo.ToString() == sourceInfoJson.dump()); } /** @@ -594,11 +594,11 @@ HWTEST_F(BmsBundleDataStorageTest, LoadAllData_0100, Function | SmallTest | Leve baseApp.name = NORMAL_BUNDLE_NAME + std::to_string(i); baseApp.bundleName = baseApp.name; innerBundleInfo.SetBaseApplicationInfo(baseApp); - ASSERT_TRUE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); + EXPECT_TRUE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); } std::map> bundleDates; - ASSERT_TRUE(bundleDataStorage.LoadAllData(bundleDates)); + EXPECT_TRUE(bundleDataStorage.LoadAllData(bundleDates)); for (int i = 0; i < count; i++) { std::string bundleName = NORMAL_BUNDLE_NAME + std::to_string(i); @@ -608,14 +608,14 @@ HWTEST_F(BmsBundleDataStorageTest, LoadAllData_0100, Function | SmallTest | Leve // search allDeviceInfos by bundle name auto bundleDatesIter = bundleDates.find(bundleName); - ASSERT_TRUE(bundleDatesIter != bundleDates.end()); + EXPECT_TRUE(bundleDatesIter != bundleDates.end()); // search InnerBundleInfo by device id auto allDeviceInfos = bundleDatesIter->second; auto devicesInfosIter = allDeviceInfos.find(deviceId_); - ASSERT_TRUE(devicesInfosIter != allDeviceInfos.end()); + EXPECT_TRUE(devicesInfosIter != allDeviceInfos.end()); InnerBundleInfo afterLoadInfo = devicesInfosIter->second; - ASSERT_TRUE(innerBundleInfo.ToString() == afterLoadInfo.ToString()); + EXPECT_TRUE(innerBundleInfo.ToString() == afterLoadInfo.ToString()); } } @@ -631,7 +631,7 @@ HWTEST_F(BmsBundleDataStorageTest, DeleteBundleData_0100, Function | SmallTest | innerBundleInfo.FromJson(innerBundleInfoJson_); BundleDataStorage bundleDataStorage; - ASSERT_TRUE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); + EXPECT_TRUE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); CheckBundleDeleted(innerBundleInfo); } @@ -647,7 +647,7 @@ HWTEST_F(BmsBundleDataStorageTest, DeleteBundleData_0200, Function | SmallTest | InnerBundleInfo innerBundleInfo; innerBundleInfo.FromJson(innerBundleInfoJson_); BundleDataStorage bundleDataStorage; - ASSERT_FALSE(bundleDataStorage.DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); + EXPECT_FALSE(bundleDataStorage.DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); } /** @@ -658,14 +658,14 @@ HWTEST_F(BmsBundleDataStorageTest, DeleteBundleData_0200, Function | SmallTest | */ HWTEST_F(BmsBundleDataStorageTest, DeleteBundleData_0300, Function | SmallTest | Level1) { - ASSERT_EQ(remove(Constants::BUNDLE_DATA_BASE_FILE.c_str()), 0); + EXPECT_EQ(remove(Constants::BUNDLE_DATA_BASE_FILE.c_str()), 0); InnerBundleInfo innerBundleInfo; innerBundleInfo.FromJson(innerBundleInfoJson_); BundleDataStorage bundleDataStorage; - ASSERT_FALSE(bundleDataStorage.DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); + EXPECT_FALSE(bundleDataStorage.DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); std::map> bundleDates; - ASSERT_FALSE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); - ASSERT_FALSE(bundleDataStorage.LoadAllData(bundleDates)); + EXPECT_FALSE(bundleDataStorage.SaveStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo)); + EXPECT_FALSE(bundleDataStorage.LoadAllData(bundleDates)); } \ No newline at end of file diff --git a/services/bundlemgr/test/unittest/bms_bundle_installer_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_bundle_installer_test/BUILD.gn old mode 100644 new mode 100755 index d53bae1274f152ca3a5daef08dfa765bb08e6b95..096d0b586298efd5f05ceae4ab7d8a5b991e0615 --- a/services/bundlemgr/test/unittest/bms_bundle_installer_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_bundle_installer_test/BUILD.gn @@ -20,7 +20,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsBundleInstallerTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${services_path}/bundlemgr/src/bundle_data_mgr.cpp", "${services_path}/bundlemgr/src/bundle_data_storage_database.cpp", @@ -32,6 +32,9 @@ ohos_unittest("BmsBundleInstallerTest") { "${services_path}/bundlemgr/src/installd/installd_host_impl.cpp", "${services_path}/bundlemgr/src/installd/installd_operator.cpp", "${services_path}/bundlemgr/src/installd/installd_service.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += [ @@ -61,6 +64,7 @@ ohos_unittest("BmsBundleInstallerTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp index 503b49c19769dd03f733c24d68738da5009c9550..58cc1e42ef71fd48cabd3cb30dd563c1e83620aa 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp @@ -140,13 +140,13 @@ void BmsBundleInstallerTest::SetUpTestCase() { if (access(ROOT_DIR.c_str(), F_OK) != 0) { bool result = OHOS::ForceCreateDirectory(ROOT_DIR); - ASSERT_TRUE(result) << "fail to create root dir"; + EXPECT_TRUE(result) << "fail to create root dir"; } if (chown(ROOT_DIR.c_str(), ROOT_UID, ROOT_UID) != 0) { - ASSERT_TRUE(false) << "fail to change root dir own ship"; + EXPECT_TRUE(false) << "fail to change root dir own ship"; } if (chmod(ROOT_DIR.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { - ASSERT_TRUE(false) << "fail to change root dir mode"; + EXPECT_TRUE(false) << "fail to change root dir mode"; } } @@ -173,19 +173,19 @@ void BmsBundleInstallerTest::TearDown() void BmsBundleInstallerTest::CheckFileExist() const { int bundleCodeExist = access(BUNDLE_CODE_DIR.c_str(), F_OK); - ASSERT_EQ(bundleCodeExist, 0) << "the bundle code dir does not exists: " << BUNDLE_CODE_DIR; + EXPECT_EQ(bundleCodeExist, 0) << "the bundle code dir does not exists: " << BUNDLE_CODE_DIR; int bundleDataExist = access(BUNDLE_DATA_DIR.c_str(), F_OK); - ASSERT_EQ(bundleDataExist, 0) << "the bundle data dir does not exists: " << BUNDLE_DATA_DIR; + EXPECT_EQ(bundleDataExist, 0) << "the bundle data dir does not exists: " << BUNDLE_DATA_DIR; } void BmsBundleInstallerTest::CheckFileNonExist() const { int bundleCodeExist = access(BUNDLE_CODE_DIR.c_str(), F_OK); - ASSERT_NE(bundleCodeExist, 0) << "the bundle code dir exists: " << BUNDLE_CODE_DIR; + EXPECT_NE(bundleCodeExist, 0) << "the bundle code dir exists: " << BUNDLE_CODE_DIR; int bundleDataExist = access(BUNDLE_DATA_DIR.c_str(), F_OK); - ASSERT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << BUNDLE_DATA_DIR; + EXPECT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << BUNDLE_DATA_DIR; } const std::shared_ptr BmsBundleInstallerTest::GetBundleDataMgr() const @@ -210,7 +210,7 @@ void BmsBundleInstallerTest::StopBundleService() return; } auto dataMgr = bundleMgrService_->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_START); dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_SUCCESS); bundleMgrService_->OnStop(); @@ -227,7 +227,7 @@ void BmsBundleInstallerTest::CreateInstallerManager() return; } manager_ = std::make_shared(installRunner); - ASSERT_NE(nullptr, manager_); + EXPECT_NE(nullptr, manager_); } void BmsBundleInstallerTest::ClearBundleInfoInDb() @@ -248,7 +248,7 @@ void BmsBundleInstallerTest::ClearBundleInfoInDb() applicationInfo.bundleName = BUNDLE_NAME; innerBundleInfo.SetBaseApplicationInfo(applicationInfo); bool result = dataStorage->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo); - ASSERT_TRUE(result) << "the bundle info in db clear fail: " << BUNDLE_NAME; + EXPECT_TRUE(result) << "the bundle info in db clear fail: " << BUNDLE_NAME; } /** @@ -261,7 +261,7 @@ HWTEST_F(BmsBundleInstallerTest, SystemInstall_0100, Function | SmallTest | Leve { std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; bool result = InstallSystemBundle(bundleFile); - ASSERT_TRUE(result) << "the bundle file install failed: " << bundleFile; + EXPECT_TRUE(result) << "the bundle file install failed: " << bundleFile; CheckFileExist(); ClearBundleInfoInDb(); } @@ -276,7 +276,7 @@ HWTEST_F(BmsBundleInstallerTest, SystemInstall_0200, Function | SmallTest | Leve { std::string nonExistFile = RESOURCE_ROOT_PATH + INVALID_BUNDLE; bool result = InstallSystemBundle(nonExistFile); - ASSERT_FALSE(result) << "the bundle file install success: " << nonExistFile; + EXPECT_FALSE(result) << "the bundle file install success: " << nonExistFile; CheckFileNonExist(); } @@ -289,7 +289,7 @@ HWTEST_F(BmsBundleInstallerTest, SystemInstall_0200, Function | SmallTest | Leve HWTEST_F(BmsBundleInstallerTest, SystemInstall_0300, Function | SmallTest | Level0) { bool result = InstallSystemBundle(""); - ASSERT_FALSE(result) << "the empty path install success"; + EXPECT_FALSE(result) << "the empty path install success"; CheckFileNonExist(); } @@ -303,7 +303,7 @@ HWTEST_F(BmsBundleInstallerTest, SystemInstall_0400, Function | SmallTest | Leve { std::string wrongBundleName = RESOURCE_ROOT_PATH + WRONG_BUNDLE_NAME; bool result = InstallSystemBundle(wrongBundleName); - ASSERT_FALSE(result) << "the wrong bundle file install success"; + EXPECT_FALSE(result) << "the wrong bundle file install success"; CheckFileNonExist(); } @@ -317,7 +317,7 @@ HWTEST_F(BmsBundleInstallerTest, SystemInstall_0500, Function | SmallTest | Leve { std::string errorFormat = RESOURCE_ROOT_PATH + FORMAT_ERROR_BUNDLE; bool result = InstallSystemBundle(errorFormat); - ASSERT_FALSE(result) << "the wrong format file install success"; + EXPECT_FALSE(result) << "the wrong format file install success"; CheckFileNonExist(); } @@ -331,7 +331,7 @@ HWTEST_F(BmsBundleInstallerTest, SystemInstall_0600, Function | SmallTest | Leve { std::string bundleFile = INVALID_PATH + RIGHT_BUNDLE; bool result = InstallSystemBundle(bundleFile); - ASSERT_FALSE(result) << "the invalid path install success"; + EXPECT_FALSE(result) << "the invalid path install success"; CheckFileNonExist(); } @@ -359,14 +359,14 @@ HWTEST_F(BmsBundleInstallerTest, SystemUpdateData_0100, Function | SmallTest | L { ApplicationInfo info; auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_FALSE(result); + EXPECT_FALSE(result); std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; bool installResult = InstallSystemBundle(bundleFile); - ASSERT_TRUE(installResult); + EXPECT_TRUE(installResult); result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_TRUE(result); + EXPECT_TRUE(result); EXPECT_EQ(info.name, BUNDLE_NAME); ClearBundleInfoInDb(); } @@ -381,12 +381,12 @@ HWTEST_F(BmsBundleInstallerTest, SystemUpdateData_0200, Function | SmallTest | L { ApplicationInfo info; auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_FALSE(result); + EXPECT_FALSE(result); std::string wrongBundleName = RESOURCE_ROOT_PATH + WRONG_BUNDLE_NAME; bool installResult = InstallSystemBundle(wrongBundleName); - ASSERT_FALSE(installResult); + EXPECT_FALSE(installResult); result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); EXPECT_FALSE(result); } @@ -400,15 +400,15 @@ HWTEST_F(BmsBundleInstallerTest, SystemUpdateData_0200, Function | SmallTest | L HWTEST_F(BmsBundleInstallerTest, SystemUpdateData_0300, Function | SmallTest | Level0) { auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); // prepare already install information. std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; bool firstInstall = InstallSystemBundle(bundleFile); - ASSERT_TRUE(firstInstall); + EXPECT_TRUE(firstInstall); ApplicationInfo info; auto result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_TRUE(result); - ASSERT_EQ(info.name, BUNDLE_NAME); + EXPECT_TRUE(result); + EXPECT_EQ(info.name, BUNDLE_NAME); bool secondInstall = InstallSystemBundle(bundleFile); EXPECT_FALSE(secondInstall); ClearBundleInfoInDb(); @@ -424,7 +424,7 @@ HWTEST_F(BmsBundleInstallerTest, SystemUpdateData_0400, Function | SmallTest | L { // prepare already install information. auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); // begin to reinstall package std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; @@ -444,7 +444,7 @@ HWTEST_F(BmsBundleInstallerTest, CreateInstallTask_0100, Function | SmallTest | { CreateInstallerManager(); sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; GetBundleInstallerManager()->CreateInstallTask(bundleFile, installParam, receiver); @@ -463,7 +463,7 @@ HWTEST_F(BmsBundleInstallerTest, CreateInstallTask_0200, Function | SmallTest | { CreateInstallerManager(); sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; std::string bundleFile = RESOURCE_ROOT_PATH + INVALID_BUNDLE; GetBundleInstallerManager()->CreateInstallTask(bundleFile, installParam, receiver); @@ -481,7 +481,7 @@ HWTEST_F(BmsBundleInstallerTest, CreateUninstallTask_0100, Function | SmallTest { CreateInstallerManager(); sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; GetBundleInstallerManager()->CreateInstallTask(bundleFile, installParam, receiver); @@ -504,7 +504,7 @@ HWTEST_F(BmsBundleInstallerTest, CreateUninstallTask_0200, Function | SmallTest { CreateInstallerManager(); sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; std::string bundleFile = RESOURCE_ROOT_PATH + INVALID_BUNDLE; GetBundleInstallerManager()->CreateUninstallTask(bundleFile, installParam, receiver); @@ -522,7 +522,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0100, Function | SmallTest | { std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; ErrCode result = InstallThirdPartyBundle(bundleFile); - ASSERT_EQ(result, ERR_OK); + EXPECT_EQ(result, ERR_OK); CheckFileExist(); ClearBundleInfoInDb(); } @@ -537,7 +537,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0200, Function | SmallTest | { std::string nonExistFile = RESOURCE_ROOT_PATH + INVALID_BUNDLE; ErrCode result = InstallThirdPartyBundle(nonExistFile); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID); CheckFileNonExist(); } @@ -550,7 +550,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0200, Function | SmallTest | HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0300, Function | SmallTest | Level0) { ErrCode result = InstallThirdPartyBundle(""); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID); CheckFileNonExist(); } @@ -564,7 +564,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0400, Function | SmallTest | { std::string wrongBundleName = RESOURCE_ROOT_PATH + WRONG_BUNDLE_NAME; ErrCode result = InstallThirdPartyBundle(wrongBundleName); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME); CheckFileNonExist(); } @@ -578,7 +578,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0500, Function | SmallTest | { std::string errorFormat = RESOURCE_ROOT_PATH + FORMAT_ERROR_BUNDLE; ErrCode result = InstallThirdPartyBundle(errorFormat); - ASSERT_EQ(result, ERR_APPEXECFWK_PARSE_NO_PROFILE); + EXPECT_EQ(result, ERR_APPEXECFWK_PARSE_NO_PROFILE); CheckFileNonExist(); } @@ -592,7 +592,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0600, Function | SmallTest | { std::string bundleFile = INVALID_PATH + RIGHT_BUNDLE; ErrCode result = InstallThirdPartyBundle(bundleFile); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID); CheckFileNonExist(); } @@ -607,7 +607,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyInstall_0700, Function | SmallTest | StopInstalldService(); std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; ErrCode result = InstallThirdPartyBundle(bundleFile); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); } /** @@ -620,14 +620,14 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyUpdateData_0100, Function | SmallTest { ApplicationInfo info; auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_FALSE(result); + EXPECT_FALSE(result); std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; ErrCode installResult = InstallThirdPartyBundle(bundleFile); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_TRUE(result); + EXPECT_TRUE(result); EXPECT_EQ(info.name, BUNDLE_NAME); ClearBundleInfoInDb(); } @@ -642,12 +642,12 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyUpdateData_0200, Function | SmallTest { ApplicationInfo info; auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_FALSE(result); + EXPECT_FALSE(result); std::string wrongBundleName = RESOURCE_ROOT_PATH + WRONG_BUNDLE_NAME; ErrCode installResult = InstallThirdPartyBundle(wrongBundleName); - ASSERT_EQ(installResult, ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME); + EXPECT_EQ(installResult, ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME); result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); EXPECT_FALSE(result); } @@ -661,15 +661,15 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyUpdateData_0200, Function | SmallTest HWTEST_F(BmsBundleInstallerTest, ThirdPartyUpdateData_0300, Function | SmallTest | Level0) { auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); // prepare already install information. std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; ErrCode firstInstall = InstallThirdPartyBundle(bundleFile); - ASSERT_EQ(firstInstall, ERR_OK); + EXPECT_EQ(firstInstall, ERR_OK); ApplicationInfo info; auto result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_TRUE(result); - ASSERT_EQ(info.name, BUNDLE_NAME); + EXPECT_TRUE(result); + EXPECT_EQ(info.name, BUNDLE_NAME); ErrCode secondInstall = InstallThirdPartyBundle(bundleFile); EXPECT_EQ(secondInstall, ERR_APPEXECFWK_INSTALL_ALREADY_EXIST); ClearBundleInfoInDb(); @@ -684,15 +684,15 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyUpdateData_0300, Function | SmallTest HWTEST_F(BmsBundleInstallerTest, ThirdPartyUpdateData_0400, Function | SmallTest | Level0) { auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); // prepare already install information. std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; ErrCode firstInstall = InstallThirdPartyBundle(bundleFile); - ASSERT_EQ(firstInstall, ERR_OK); + EXPECT_EQ(firstInstall, ERR_OK); ApplicationInfo info; auto result = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, info); - ASSERT_TRUE(result); - ASSERT_EQ(info.name, BUNDLE_NAME); + EXPECT_TRUE(result); + EXPECT_EQ(info.name, BUNDLE_NAME); ErrCode secondInstall = UpdateThirdPartyBundle(bundleFile); EXPECT_EQ(secondInstall, ERR_OK); ClearBundleInfoInDb(); @@ -708,7 +708,7 @@ HWTEST_F(BmsBundleInstallerTest, ThirdPartyUpdateData_0500, Function | SmallTest { // prepare already install information. auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); // begin to reinstall package std::string bundleFile = RESOURCE_ROOT_PATH + RIGHT_BUNDLE; diff --git a/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/BUILD.gn old mode 100644 new mode 100755 index 455cd359a6845a65c3079232700bf7087b1eef19..f5277266f461ac90356b90df2375bf974ffa97fa --- a/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/BUILD.gn @@ -20,7 +20,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsBundleKitServiceTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${innerkits_path}/appexecfwk_base/src/ability_info.cpp", "${innerkits_path}/appexecfwk_base/src/application_info.cpp", @@ -37,6 +37,9 @@ ohos_unittest("BmsBundleKitServiceTest") { "${services_path}/bundlemgr/src/installd/installd_host_impl.cpp", "${services_path}/bundlemgr/src/installd/installd_operator.cpp", "${services_path}/bundlemgr/src/installd/installd_service.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += [ @@ -63,12 +66,14 @@ ohos_unittest("BmsBundleKitServiceTest") { "${libs_path}/libeventhandler:libeventhandler_target", "//base/security/appverify/interfaces/innerkits/appverify:libhapverify", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] deps += bundle_install_deps diff --git a/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/bms_bundle_kit_service_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/bms_bundle_kit_service_test.cpp index f22f17d43af68277300fdc346b59993fd5138181..a6a48a3a7bb70c714abea361dd45b7299e3a037d 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/bms_bundle_kit_service_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_kit_service_test/bms_bundle_kit_service_test.cpp @@ -15,7 +15,8 @@ #include #include - +#include "ability_manager_client.h" +#include #include "directory_ex.h" #include "bundle_data_mgr.h" #include "install_param.h" @@ -27,6 +28,8 @@ #include "inner_bundle_info.h" #include "mock_clean_cache.h" #include "mock_bundle_status.h" +#include "ohos/aafwk/content/want.h" +#include "module_usage_data_storage.h" using namespace testing::ext; using namespace OHOS; @@ -37,6 +40,7 @@ namespace { const std::string BUNDLE_NAME_TEST = "com.example.bundlekit.test"; const std::string MODULE_NAME_TEST = "com.example.bundlekit.test.entry"; +const std::string ABILITY_NAME_TEST1 = ".Reading1"; const std::string ABILITY_NAME_TEST = ".Reading"; const int TEST_UID = 1001; const std::string BUNDLE_LABEL = "Hello, OHOS"; @@ -48,6 +52,7 @@ const int32_t BUNDLE_MAX_SDK_VERSION = 0; const int32_t BUNDLE_MIN_SDK_VERSION = 0; const std::string BUNDLE_JOINT_USERID = "3"; const uint32_t BUNDLE_VERSION_CODE = 1001; +const std::string BUNDLE_NAME_TEST1 = "com.example.bundlekit.test1"; const std::string BUNDLE_NAME_DEMO = "com.example.bundlekit.demo"; const std::string MODULE_NAME_DEMO = "com.example.bundlekit.demo.entry"; const std::string ABILITY_NAME_DEMO = ".Writing"; @@ -56,7 +61,7 @@ const std::string PACKAGE_NAME = "com.example.bundlekit.test.entry"; const std::string PROCESS_TEST = "test.process"; const std::string DEVICE_ID = "PHONE-001"; const int APPLICATION_INFO_FLAGS = 1; -const int DEFAULT_USER_ID = 0; +const int DEFAULT_USER_ID_TEST = 0; const std::string LABEL = "hello"; const std::string DESCRIPTION = "mainEntry"; const std::string THEME = "mytheme"; @@ -71,6 +76,7 @@ const AbilityType ABILITY_TYPE = AbilityType::PAGE; const DisplayOrientation ORIENTATION = DisplayOrientation::PORTRAIT; const LaunchMode LAUNCH_MODE = LaunchMode::SINGLETON; const uint32_t FORM_ENTITY = 1; +const std::vector CONFIG_CHANGES = {"locale"}; const int DEFAULT_FORM_HEIGHT = 100; const int DEFAULT_FORM_WIDTH = 200; const std::string META_DATA_DESCRIPTION = "description"; @@ -92,6 +98,7 @@ const uint32_t BUNDLE_NAMES_SIZE_ZERO = 0; const uint32_t BUNDLE_NAMES_SIZE_ONE = 1; const std::string EMPTY_STRING = ""; const int INVALID_UID = -1; +const std::string ABILITY_URI = "dataability:///com.example.hiworld.himusic.UserADataAbility/person/10"; const std::string URI = "dataability://com.example.hiworld.himusic.UserADataAbility"; const std::string ERROR_URI = "dataability://"; const std::string HAP_FILE_PATH = "/data/test/resource/bms/bundle_kit/test.hap"; @@ -125,7 +132,6 @@ const std::string SHORTCUT_LABEL = "shortcutLabel"; const std::string SHORTCUT_DISABLE_MESSAGE = "shortcutDisableMessage"; const std::string SHORTCUT_INTENTS_TARGET_BUNDLE = "targetBundle"; const std::string SHORTCUT_INTENTS_TARGET_CLASS = "targetClass"; -const int FORMINFO_DESCRIPTIONID = 123; } // namespace @@ -137,6 +143,8 @@ public: void SetUp(); void TearDown(); std::shared_ptr GetBundleDataMgr() const; + void MockInnerBundleInfo(const std::string &bundleName, const std::string &moduleName, + const std::string &abilityName, InnerBundleInfo &innerBundleInfo) const; void MockInstallBundle( const std::string &bundleName, const std::string &moduleName, const std::string &abilityName) const; void MockUninstallBundle(const std::string &bundleName) const; @@ -233,7 +241,7 @@ void BmsBundleKitServiceTest::MockInstallBundle( ReqPermission reqPermission2 = {.name = "permission1"}; moduleInfo.reqPermissions = {reqPermission1, reqPermission2}; moduleInfo.modulePackage = PACKAGE_NAME; - moduleInfo.moduleName = PACKAGE_NAME; + moduleInfo.moduleName = moduleName; moduleInfo.description = BUNDLE_DESCRIPTION; moduleInfo.colorMode = COLOR_MODE; @@ -262,26 +270,25 @@ void BmsBundleKitServiceTest::MockInstallBundle( } std::vector formInfos; formInfos.emplace_back(form); - if(bundleName == BUNDLE_NAME_TEST) { + if (bundleName == BUNDLE_NAME_TEST) { ShortcutInfo shortcut = MockShortcutInfo(bundleName, SHORTCUT_TEST_ID); std::string shortcutKey = bundleName + moduleName + SHORTCUT_TEST_ID; innerBundleInfo.InsertShortcutInfos(shortcutKey, shortcut); - } - else { + } else { ShortcutInfo shortcut = MockShortcutInfo(bundleName, SHORTCUT_DEMO_ID); std::string shortcutKey = bundleName + moduleName + SHORTCUT_DEMO_ID; innerBundleInfo.InsertShortcutInfos(shortcutKey, shortcut); } innerBundleInfo.InsertFormInfos(keyName, formInfos); auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool startRet = dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_START); bool finishRet = dataMgr->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS); bool addRet = dataMgr->AddInnerBundleInfo(bundleName, innerBundleInfo); - ASSERT_TRUE(startRet); - ASSERT_TRUE(finishRet); - ASSERT_TRUE(addRet); + EXPECT_TRUE(startRet); + EXPECT_TRUE(finishRet); + EXPECT_TRUE(addRet); } FormInfo BmsBundleKitServiceTest::MockFormInfo( @@ -293,7 +300,7 @@ FormInfo BmsBundleKitServiceTest::MockFormInfo( formInfo.abilityName = abilityName; formInfo.moduleName = moduleName; formInfo.package = PACKAGE_NAME; - formInfo.descriptionId = FORMINFO_DESCRIPTIONID; + formInfo.descriptionId = 123; formInfo.formConfigAbility = FORM_PATH; formInfo.description = FORM_DESCRIPTION; formInfo.defaultFlag = false; @@ -316,7 +323,8 @@ FormInfo BmsBundleKitServiceTest::MockFormInfo( return formInfo; } -ShortcutInfo BmsBundleKitServiceTest::MockShortcutInfo(const std::string &bundleName, const std::string &shortcutId) const +ShortcutInfo BmsBundleKitServiceTest::MockShortcutInfo( + const std::string &bundleName, const std::string &shortcutId) const { ShortcutInfo shortcutInfos; shortcutInfos.id = shortcutId; @@ -338,12 +346,12 @@ ShortcutInfo BmsBundleKitServiceTest::MockShortcutInfo(const std::string &bundle void BmsBundleKitServiceTest::MockUninstallBundle(const std::string &bundleName) const { auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool startRet = dataMgr->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START); bool finishRet = dataMgr->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_SUCCESS); - ASSERT_TRUE(startRet); - ASSERT_TRUE(finishRet); + EXPECT_TRUE(startRet); + EXPECT_TRUE(finishRet); } AbilityInfo BmsBundleKitServiceTest::MockAbilityInfo( @@ -364,6 +372,7 @@ AbilityInfo BmsBundleKitServiceTest::MockAbilityInfo( abilityInfo.type = ABILITY_TYPE; abilityInfo.orientation = ORIENTATION; abilityInfo.launchMode = LAUNCH_MODE; + abilityInfo.configChanges = {"locale"}; abilityInfo.formEntity = 1; abilityInfo.defaultFormHeight = DEFAULT_FORM_HEIGHT; abilityInfo.defaultFormWidth = DEFAULT_FORM_WIDTH; @@ -372,6 +381,7 @@ AbilityInfo BmsBundleKitServiceTest::MockAbilityInfo( abilityInfo.libPath = LIB_PATH; abilityInfo.uri = URI; abilityInfo.enabled = true; + abilityInfo.supportPipMode = false; abilityInfo.targetAbility = TARGET_ABILITY; AppExecFwk::Parameters parameters{"description", "name", "type"}; AppExecFwk::Results results{"description", "name", "type"}; @@ -381,6 +391,25 @@ AbilityInfo BmsBundleKitServiceTest::MockAbilityInfo( return abilityInfo; } +void BmsBundleKitServiceTest::MockInnerBundleInfo(const std::string &bundleName, const std::string &moduleName, + const std::string &abilityName, InnerBundleInfo &innerBundleInfo) const +{ + ApplicationInfo appInfo; + appInfo.bundleName = bundleName; + BundleInfo bundleInfo; + bundleInfo.name = bundleName; + innerBundleInfo.SetBaseBundleInfo(bundleInfo); + InnerModuleInfo moduleInfo; + moduleInfo.modulePackage = moduleName; + moduleInfo.moduleName = moduleName; + moduleInfo.description = BUNDLE_DESCRIPTION; + innerBundleInfo.InsertInnerModuleInfo(moduleName, moduleInfo); + AbilityInfo abilityInfo = MockAbilityInfo(bundleName, moduleName, abilityName); + std::string keyName = bundleName + moduleName + abilityName; + innerBundleInfo.InsertAbilitiesInfo(keyName, abilityInfo); + innerBundleInfo.SetBaseApplicationInfo(appInfo); +} + void BmsBundleKitServiceTest::CheckBundleInfo(const std::string &bundleName, const std::string &moduleName, const uint32_t abilitySize, const BundleInfo &bundleInfo) const { @@ -451,25 +480,27 @@ void BmsBundleKitServiceTest::CheckAbilityInfo( EXPECT_EQ(ORIENTATION, abilityInfo.orientation); EXPECT_EQ(LAUNCH_MODE, abilityInfo.launchMode); EXPECT_EQ(URI, abilityInfo.uri); + EXPECT_EQ(false, abilityInfo.supportPipMode); EXPECT_EQ(TARGET_ABILITY, abilityInfo.targetAbility); + EXPECT_EQ(CONFIG_CHANGES, abilityInfo.configChanges); EXPECT_EQ(FORM_ENTITY, abilityInfo.formEntity); EXPECT_EQ(DEFAULT_FORM_HEIGHT, abilityInfo.defaultFormHeight); EXPECT_EQ(DEFAULT_FORM_WIDTH, abilityInfo.defaultFormWidth); for (auto &info : abilityInfo.metaData.customizeData) { - EXPECT_EQ(info.name, META_DATA_NAME); - EXPECT_EQ(info.value, META_DATA_VALUE); - EXPECT_EQ(info.extra, META_DATA_EXTRA); - } + EXPECT_EQ(info.name, META_DATA_NAME); + EXPECT_EQ(info.value, META_DATA_VALUE); + EXPECT_EQ(info.extra, META_DATA_EXTRA); + } for (auto &info : abilityInfo.metaData.parameters) { - EXPECT_EQ(info.description, META_DATA_DESCRIPTION); - EXPECT_EQ(info.name, META_DATA_NAME); - EXPECT_EQ(info.type, META_DATA_TYPE); - } + EXPECT_EQ(info.description, META_DATA_DESCRIPTION); + EXPECT_EQ(info.name, META_DATA_NAME); + EXPECT_EQ(info.type, META_DATA_TYPE); + } for (auto &info : abilityInfo.metaData.results) { - EXPECT_EQ(info.description, META_DATA_DESCRIPTION); - EXPECT_EQ(info.name, META_DATA_NAME); - EXPECT_EQ(info.type, META_DATA_TYPE); - } + EXPECT_EQ(info.description, META_DATA_DESCRIPTION); + EXPECT_EQ(info.name, META_DATA_NAME); + EXPECT_EQ(info.type, META_DATA_TYPE); + } } void BmsBundleKitServiceTest::CheckCompatibleAbilityInfo( @@ -489,7 +520,6 @@ void BmsBundleKitServiceTest::CheckCompatibleAbilityInfo( EXPECT_EQ(FORM_ENTITY, abilityInfo.formEntity); EXPECT_EQ(DEFAULT_FORM_HEIGHT, abilityInfo.defaultFormHeight); EXPECT_EQ(DEFAULT_FORM_WIDTH, abilityInfo.defaultFormWidth); - } void BmsBundleKitServiceTest::CheckCompatibleApplicationInfo( const std::string &bundleName, const uint32_t permissionSize, const CompatibleApplicationInfo &appInfo) const @@ -581,12 +611,12 @@ void BmsBundleKitServiceTest::CreateFileDir() const if (access(TEST_FILE_DIR.c_str(), F_OK) != 0) { bool result = OHOS::ForceCreateDirectory(TEST_FILE_DIR); - ASSERT_TRUE(result) << "fail to create file dir"; + EXPECT_TRUE(result) << "fail to create file dir"; } if (access(TEST_CACHE_DIR.c_str(), F_OK) != 0) { bool result = OHOS::ForceCreateDirectory(TEST_CACHE_DIR); - ASSERT_TRUE(result) << "fail to create cache dir"; + EXPECT_TRUE(result) << "fail to create cache dir"; } } @@ -601,25 +631,25 @@ void BmsBundleKitServiceTest::CleanFileDir() const void BmsBundleKitServiceTest::CheckFileExist() const { int dataExist = access(TEST_FILE_DIR.c_str(), F_OK); - ASSERT_EQ(dataExist, 0); + EXPECT_EQ(dataExist, 0); } void BmsBundleKitServiceTest::CheckFileNonExist() const { int dataExist = access(TEST_FILE_DIR.c_str(), F_OK); - ASSERT_NE(dataExist, 0); + EXPECT_NE(dataExist, 0); } void BmsBundleKitServiceTest::CheckCacheExist() const { int dataExist = access(TEST_CACHE_DIR.c_str(), F_OK); - ASSERT_EQ(dataExist, 0); + EXPECT_EQ(dataExist, 0); } void BmsBundleKitServiceTest::CheckCacheNonExist() const { int dataExist = access(TEST_CACHE_DIR.c_str(), F_OK); - ASSERT_NE(dataExist, 0); + EXPECT_NE(dataExist, 0); } void BmsBundleKitServiceTest::CheckFormInfoTest(const std::vector &formInfos) const @@ -634,7 +664,7 @@ void BmsBundleKitServiceTest::CheckFormInfoTest(const std::vector &for EXPECT_EQ(formInfo.defaultFlag, false); EXPECT_EQ(formInfo.type, FormType::JS); EXPECT_EQ(formInfo.colorMode, FormsColorMode::LIGHT_MODE); - EXPECT_EQ(formInfo.descriptionId, FORMINFO_DESCRIPTIONID); + EXPECT_EQ(formInfo.descriptionId, 123); EXPECT_EQ(formInfo.deepLink, FORM_PATH); EXPECT_EQ(formInfo.package, PACKAGE_NAME); EXPECT_EQ(formInfo.formVisibleNotify, true); @@ -664,7 +694,7 @@ void BmsBundleKitServiceTest::CheckFormInfoDemo(const std::vector &for EXPECT_EQ(formInfo.defaultFlag, false); EXPECT_EQ(formInfo.type, FormType::JS); EXPECT_EQ(formInfo.colorMode, FormsColorMode::LIGHT_MODE); - EXPECT_EQ(formInfo.descriptionId, FORMINFO_DESCRIPTIONID); + EXPECT_EQ(formInfo.descriptionId, 123); EXPECT_EQ(formInfo.deepLink, FORM_PATH); EXPECT_EQ(formInfo.package, PACKAGE_NAME); EXPECT_EQ(formInfo.formVisibleNotify, true); @@ -790,7 +820,7 @@ HWTEST_F(BmsBundleKitServiceTest, GetBundleInfo_0400, Function | SmallTest | Lev { BundleInfo bundleInfo; bool ret = GetBundleDataMgr()->GetBundleInfo(BUNDLE_NAME_TEST, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_FALSE(ret); + EXPECT_FALSE(ret); EXPECT_EQ(EMPTY_STRING, bundleInfo.name); EXPECT_EQ(EMPTY_STRING, bundleInfo.label); } @@ -831,7 +861,7 @@ HWTEST_F(BmsBundleKitServiceTest, GetBundleInfos_0100, Function | SmallTest | Le std::vector bundleInfos; bool ret = GetBundleDataMgr()->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos); - ASSERT_TRUE(ret); + EXPECT_TRUE(ret); CheckInstalledBundleInfos(ABILITY_SIZE_ZERO, bundleInfos); MockUninstallBundle(BUNDLE_NAME_TEST); @@ -851,7 +881,7 @@ HWTEST_F(BmsBundleKitServiceTest, GetBundleInfos_0200, Function | SmallTest | Le std::vector bundleInfos; bool ret = GetBundleDataMgr()->GetBundleInfos(BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfos); - ASSERT_TRUE(ret); + EXPECT_TRUE(ret); CheckInstalledBundleInfos(ABILITY_SIZE_ONE, bundleInfos); MockUninstallBundle(BUNDLE_NAME_TEST); @@ -868,7 +898,7 @@ HWTEST_F(BmsBundleKitServiceTest, GetBundleInfos_0300, Function | SmallTest | Le { std::vector bundleInfos; bool ret = GetBundleDataMgr()->GetBundleInfos(BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfos); - ASSERT_FALSE(ret); + EXPECT_FALSE(ret); } /** @@ -884,13 +914,13 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfo_0100, Function | SmallTest ApplicationInfo testResult; bool testRet = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, testResult); + BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, testResult); EXPECT_TRUE(testRet); CheckApplicationInfo(BUNDLE_NAME_TEST, PERMISSION_SIZE_ZERO, testResult); ApplicationInfo demoResult; bool demoRet = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_DEMO, ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, DEFAULT_USER_ID, demoResult); + BUNDLE_NAME_DEMO, ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, DEFAULT_USER_ID_TEST, demoResult); EXPECT_TRUE(demoRet); CheckApplicationInfo(BUNDLE_NAME_DEMO, PERMISSION_SIZE_TWO, demoResult); @@ -910,7 +940,7 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfo_0200, Function | SmallTest ApplicationInfo result; bool ret = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_DEMO, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, result); + BUNDLE_NAME_DEMO, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, result); EXPECT_FALSE(ret); EXPECT_EQ(EMPTY_STRING, result.name); @@ -929,7 +959,7 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfo_0300, Function | SmallTest ApplicationInfo result; bool ret = GetBundleDataMgr()->GetApplicationInfo( - EMPTY_STRING, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, result); + EMPTY_STRING, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, result); EXPECT_FALSE(ret); EXPECT_EQ(EMPTY_STRING, result.name); @@ -946,8 +976,8 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfo_0400, Function | SmallTest { ApplicationInfo result; bool ret = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, result); - ASSERT_FALSE(ret); + BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, result); + EXPECT_FALSE(ret); EXPECT_EQ(EMPTY_STRING, result.name); EXPECT_EQ(EMPTY_STRING, result.label); } @@ -964,7 +994,7 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfo_0500, Function | SmallTest ApplicationInfo result; bool ret = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, result); + BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, result); EXPECT_TRUE(ret); Parcel parcel; parcel.WriteParcelable(&result); @@ -988,9 +1018,9 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfos_0100, Function | SmallTest MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); std::vector appInfos; - bool ret = - GetBundleDataMgr()->GetApplicationInfos(ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, appInfos); - ASSERT_TRUE(ret); + bool ret = GetBundleDataMgr()->GetApplicationInfos( + ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, appInfos); + EXPECT_TRUE(ret); CheckInstalledApplicationInfos(PERMISSION_SIZE_ZERO, appInfos); MockUninstallBundle(BUNDLE_NAME_TEST); @@ -1010,8 +1040,8 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfos_0200, Function | SmallTest std::vector appInfos; bool ret = GetBundleDataMgr()->GetApplicationInfos( - ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, DEFAULT_USER_ID, appInfos); - ASSERT_TRUE(ret); + ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, DEFAULT_USER_ID_TEST, appInfos); + EXPECT_TRUE(ret); CheckInstalledApplicationInfos(PERMISSION_SIZE_TWO, appInfos); MockUninstallBundle(BUNDLE_NAME_TEST); @@ -1028,8 +1058,8 @@ HWTEST_F(BmsBundleKitServiceTest, GetApplicationInfos_0300, Function | SmallTest { std::vector appInfos; bool ret = GetBundleDataMgr()->GetApplicationInfos( - ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, DEFAULT_USER_ID, appInfos); - ASSERT_FALSE(ret); + ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, DEFAULT_USER_ID_TEST, appInfos); + EXPECT_FALSE(ret); } /** @@ -1501,7 +1531,7 @@ HWTEST_F(BmsBundleKitServiceTest, QueryAbilityInfoByUri_0100, Function | SmallTe MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); AbilityInfo result; - bool testRet = GetBundleDataMgr()->QueryAbilityInfoByUri(URI, result); + bool testRet = GetBundleDataMgr()->QueryAbilityInfoByUri(ABILITY_URI, result); EXPECT_EQ(true, testRet); EXPECT_EQ(ABILITY_NAME_TEST, result.name); EXPECT_NE(ABILITY_NAME_DEMO, result.name); @@ -1521,7 +1551,7 @@ HWTEST_F(BmsBundleKitServiceTest, QueryAbilityInfoByUri_0200, Function | SmallTe MockInstallBundle(BUNDLE_NAME_DEMO, MODULE_NAME_TEST, ABILITY_NAME_TEST); AbilityInfo result; - bool testRet = GetBundleDataMgr()->QueryAbilityInfoByUri(URI, result); + bool testRet = GetBundleDataMgr()->QueryAbilityInfoByUri(ABILITY_URI, result); EXPECT_EQ(true, testRet); EXPECT_EQ(ABILITY_NAME_TEST, result.name); EXPECT_NE(ABILITY_NAME_DEMO, result.name); @@ -1540,7 +1570,7 @@ HWTEST_F(BmsBundleKitServiceTest, QueryAbilityInfoByUri_0200, Function | SmallTe HWTEST_F(BmsBundleKitServiceTest, QueryAbilityInfoByUri_0300, Function | SmallTest | Level1) { AbilityInfo result; - bool testRet = GetBundleDataMgr()->QueryAbilityInfoByUri(URI, result); + bool testRet = GetBundleDataMgr()->QueryAbilityInfoByUri(ABILITY_URI, result); EXPECT_EQ(false, testRet); } @@ -2051,7 +2081,7 @@ HWTEST_F(BmsBundleKitServiceTest, RegisterBundleStatus_0100, Function | SmallTes EXPECT_TRUE(result); bool resultNotify = GetBundleDataMgr()->NotifyBundleStatus( - HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL); + HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL, Constants::INVALID_UID); EXPECT_TRUE(resultNotify); int32_t callbackResult = bundleStatusCallback->GetResultCode(); @@ -2071,8 +2101,8 @@ HWTEST_F(BmsBundleKitServiceTest, RegisterBundleStatus_0200, Function | SmallTes bool result = GetBundleDataMgr()->RegisterBundleStatusCallback(bundleStatusCallback); EXPECT_TRUE(result); - bool resultNotify = - GetBundleDataMgr()->NotifyBundleStatus("", HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL); + bool resultNotify = GetBundleDataMgr()->NotifyBundleStatus( + "", HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL, Constants::INVALID_UID); EXPECT_TRUE(resultNotify); int32_t callbackResult = bundleStatusCallback->GetResultCode(); @@ -2093,7 +2123,7 @@ HWTEST_F(BmsBundleKitServiceTest, RegisterBundleStatus_0300, Function | SmallTes EXPECT_TRUE(result); bool resultNotify = GetBundleDataMgr()->NotifyBundleStatus( - ERROR_HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL); + ERROR_HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL, Constants::INVALID_UID); EXPECT_TRUE(resultNotify); int32_t callbackResult = bundleStatusCallback->GetResultCode(); @@ -2122,14 +2152,14 @@ HWTEST_F(BmsBundleKitServiceTest, ClearBundleStatus_0100, Function | SmallTest | EXPECT_TRUE(result); bool resultNotify = GetBundleDataMgr()->NotifyBundleStatus( - HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL); + HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL, Constants::INVALID_UID); EXPECT_TRUE(resultNotify); int32_t callbackResult = bundleStatusCallback->GetResultCode(); EXPECT_EQ(callbackResult, ERR_OK); bool resultNotify1 = GetBundleDataMgr()->NotifyBundleStatus( - HAP_FILE_PATH1, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL); + HAP_FILE_PATH1, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL, Constants::INVALID_UID); EXPECT_TRUE(resultNotify1); int32_t callbackResult1 = bundleStatusCallback1->GetResultCode(); @@ -2158,14 +2188,14 @@ HWTEST_F(BmsBundleKitServiceTest, UnregisterBundleStatus_0100, Function | SmallT EXPECT_TRUE(result2); bool resultNotify = GetBundleDataMgr()->NotifyBundleStatus( - HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL); + HAP_FILE_PATH, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL, Constants::INVALID_UID); EXPECT_TRUE(resultNotify); int32_t callbackResult = bundleStatusCallback->GetResultCode(); EXPECT_EQ(callbackResult, ERR_TIMED_OUT); bool resultNotify1 = GetBundleDataMgr()->NotifyBundleStatus( - HAP_FILE_PATH1, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL); + HAP_FILE_PATH1, HAP_FILE_PATH, ABILITY_NAME_DEMO, ERR_OK, NotifyType::INSTALL, Constants::INVALID_UID); EXPECT_TRUE(resultNotify1); int32_t callbackResult1 = bundleStatusCallback1->GetResultCode(); @@ -2789,6 +2819,186 @@ HWTEST_F(BmsBundleKitServiceTest, GetShortcutInfos_0500, Function | SmallTest | EXPECT_TRUE(shortcutInfos.empty()); } +/** + * @tc.number: GetUsageRecords_0100 + * @tc.name: test can get usage records by notify activity life status + * @tc.desc: 1.can get usage records + */ +HWTEST_F(BmsBundleKitServiceTest, GetUsageRecords_0100, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + auto ret = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, 1629094922); + EXPECT_TRUE(ret); + std::vector records; + auto result = GetBundleDataMgr()->GetUsageRecords(100, records); + EXPECT_TRUE(result); + auto iter = std::find_if(records.begin(), records.end(), [](const auto &item) { + return (item.bundleName == BUNDLE_NAME_TEST && item.name == MODULE_NAME_TEST && + item.abilityName == ABILITY_NAME_TEST); + }); + EXPECT_NE(iter, records.end()); + uint32_t count = 1; + EXPECT_EQ(iter->launchedCount, count); + InnerBundleInfo innerBundleInfo; + MockInnerBundleInfo(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST, innerBundleInfo); + ModuleUsageRecordStorage moduleUsageRecordStorage; + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo, 0); + MockUninstallBundle(BUNDLE_NAME_TEST); +} + +/** + * @tc.number: GetUsageRecords_0200 + * @tc.name: test can get usage records by notify activity life status + * @tc.desc: 1.no other ability have been activitied + * 2.can get two bundle usage records + */ +HWTEST_F(BmsBundleKitServiceTest, GetUsageRecords_0200, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + MockInstallBundle(BUNDLE_NAME_DEMO, MODULE_NAME_DEMO, ABILITY_NAME_DEMO); + int64_t time = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto ret = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, time); + auto ret1 = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_DEMO, ABILITY_NAME_DEMO, time); + EXPECT_TRUE(ret); + EXPECT_TRUE(ret1); + std::vector records; + auto result = GetBundleDataMgr()->GetUsageRecords(100, records); + EXPECT_TRUE(result); + size_t size = 2; + EXPECT_EQ(records.size(), size); + auto iter = std::find_if(records.begin(), records.end(), [](const auto &item) { + return (item.bundleName == BUNDLE_NAME_TEST && item.name == MODULE_NAME_TEST && + item.abilityName == ABILITY_NAME_TEST); + }); + EXPECT_NE(iter, records.end()); + uint32_t count = 1; + EXPECT_EQ(iter->launchedCount, count); + InnerBundleInfo innerBundleInfo1; + InnerBundleInfo innerBundleInfo2; + MockInnerBundleInfo(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST, innerBundleInfo1); + MockInnerBundleInfo(BUNDLE_NAME_DEMO, ABILITY_NAME_DEMO, ABILITY_NAME_DEMO, innerBundleInfo2); + ModuleUsageRecordStorage moduleUsageRecordStorage; + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo1, 0); + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo2, 0); + MockUninstallBundle(BUNDLE_NAME_TEST); + MockUninstallBundle(BUNDLE_NAME_DEMO); +} + +/** + * @tc.number: GetUsageRecords_0300 + * @tc.name: test can get usage records by notify activity life status + * @tc.desc: 1.can get usage records called two notify activity + */ +HWTEST_F(BmsBundleKitServiceTest, GetUsageRecords_0300, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + int64_t time = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto ret = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, time); + auto ret1 = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, time); + EXPECT_TRUE(ret); + EXPECT_TRUE(ret1); + std::vector records; + auto result = GetBundleDataMgr()->GetUsageRecords(100, records); + EXPECT_TRUE(result); + auto iter = std::find_if(records.begin(), records.end(), [](const auto &item) { + return (item.bundleName == BUNDLE_NAME_TEST && item.name == MODULE_NAME_TEST && + item.abilityName == ABILITY_NAME_TEST); + }); + EXPECT_NE(iter, records.end()); + uint32_t count = 2; + EXPECT_EQ(iter->launchedCount, count); + InnerBundleInfo innerBundleInfo1; + MockInnerBundleInfo(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST, innerBundleInfo1); + ModuleUsageRecordStorage moduleUsageRecordStorage; + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo1, 0); + MockUninstallBundle(BUNDLE_NAME_TEST); +} + +/** + * @tc.number: NotifyActivityLifeStatus_0100 + * @tc.name: test can called notify activity life status + * @tc.desc: 1. have called notify activity life status + * 2. called notify activity life + */ +HWTEST_F(BmsBundleKitServiceTest, NotifyActivityLifeStatus_0100, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_DEMO, ABILITY_NAME_TEST); + int64_t time = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto ret = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, time); + EXPECT_TRUE(ret); + InnerBundleInfo innerBundleInfo; + MockInnerBundleInfo(BUNDLE_NAME_TEST, MODULE_NAME_DEMO, ABILITY_NAME_TEST, innerBundleInfo); + ModuleUsageRecordStorage moduleUsageRecordStorage; + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo, 0); + MockUninstallBundle(BUNDLE_NAME_TEST); +} + +/** + * @tc.number: NotifyActivityLifeStatus_0200 + * @tc.name: test can called notify activity life status + * @tc.desc: 1. have two bundle to called notify activity life status + * 2. notify activity life + */ +HWTEST_F(BmsBundleKitServiceTest, NotifyActivityLifeStatus_0200, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + MockInstallBundle(BUNDLE_NAME_DEMO, MODULE_NAME_DEMO, ABILITY_NAME_DEMO); + int64_t time = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto ret = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_DEMO, ABILITY_NAME_DEMO, time); + auto ret1 = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, time); + EXPECT_TRUE(ret); + EXPECT_TRUE(ret1); + InnerBundleInfo innerBundleInfo1; + InnerBundleInfo innerBundleInfo2; + MockInnerBundleInfo(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST, innerBundleInfo1); + MockInnerBundleInfo(BUNDLE_NAME_DEMO, MODULE_NAME_DEMO, ABILITY_NAME_DEMO, innerBundleInfo2); + ModuleUsageRecordStorage moduleUsageRecordStorage; + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo1, 0); + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo2, 0); + MockUninstallBundle(BUNDLE_NAME_DEMO); + MockUninstallBundle(BUNDLE_NAME_TEST); +} + +/** + * @tc.number: NotifyActivityLifeStatus_0300 + * @tc.name: test can't called notify activity life status by error bundleName + * @tc.desc: 1. can't to called notify activity life status + */ +HWTEST_F(BmsBundleKitServiceTest, NotifyActivityLifeStatus_0300, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + int64_t time = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto ret = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_DEMO, ABILITY_NAME_DEMO, time); + EXPECT_FALSE(ret); + InnerBundleInfo innerBundleInfo; + MockInnerBundleInfo(BUNDLE_NAME_DEMO, MODULE_NAME_TEST, ABILITY_NAME_DEMO, innerBundleInfo); + ModuleUsageRecordStorage moduleUsageRecordStorage; + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo, 0); + MockUninstallBundle(BUNDLE_NAME_TEST); +} + +/** + * @tc.number: NotifyActivityLifeStatus_0400 + * @tc.name: test can't called notify activity life status by null bundleName + * @tc.desc: 1. can't to called notify activity life status + */ +HWTEST_F(BmsBundleKitServiceTest, NotifyActivityLifeStatus_0400, Function | SmallTest | Level1) +{ + int64_t time = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + auto ret = GetBundleDataMgr()->NotifyActivityLifeStatus(BUNDLE_NAME_DEMO, ABILITY_NAME_DEMO, time); + InnerBundleInfo innerBundleInfo; + MockInnerBundleInfo(BUNDLE_NAME_DEMO, MODULE_NAME_TEST, ABILITY_NAME_DEMO, innerBundleInfo); + ModuleUsageRecordStorage moduleUsageRecordStorage; + moduleUsageRecordStorage.DeleteUsageRecord(innerBundleInfo, 0); + EXPECT_FALSE(ret); +} + /** * @tc.number: Ability_0100 * @tc.name: test can get the compatibleAbilityInfo by one bundle @@ -2848,7 +3058,7 @@ HWTEST_F(BmsBundleKitServiceTest, Application_0100, Function | SmallTest | Level ApplicationInfo testResult; bool testRet = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, testResult); + BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, testResult); EXPECT_TRUE(testRet); CompatibleApplicationInfo appInfo; testResult.ConvertToCompatibleApplicationInfo(appInfo); @@ -2869,7 +3079,7 @@ HWTEST_F(BmsBundleKitServiceTest, Application_0200, Function | SmallTest | Level ApplicationInfo testResult1; bool testRet1 = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, testResult1); + BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, testResult1); EXPECT_TRUE(testRet1); CompatibleApplicationInfo appInfo1; testResult1.ConvertToCompatibleApplicationInfo(appInfo1); @@ -2877,11 +3087,11 @@ HWTEST_F(BmsBundleKitServiceTest, Application_0200, Function | SmallTest | Level ApplicationInfo testResult2; bool testRet2 = GetBundleDataMgr()->GetApplicationInfo( - BUNDLE_NAME_DEMO, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID, testResult2); + BUNDLE_NAME_DEMO, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, testResult2); EXPECT_TRUE(testRet2); CompatibleApplicationInfo appInfo2; testResult2.ConvertToCompatibleApplicationInfo(appInfo2); CheckCompatibleApplicationInfo(BUNDLE_NAME_DEMO, PERMISSION_SIZE_ZERO, appInfo2); MockUninstallBundle(BUNDLE_NAME_TEST); MockUninstallBundle(BUNDLE_NAME_DEMO); -} +} \ No newline at end of file diff --git a/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp index c2c1923a49b465e7460f30b74f30630dcc647e0c..8f1aa7514c2417f95768b403b00701f92cf7daca 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp @@ -104,6 +104,7 @@ const nlohmann::json CONFIG_JSON = R"( "type": "JS", "colorMode": "auto", "isDefault": false, + "jsComponentName": "card4x4", "updateEnabled": true, "scheduledUpdateTime": "21:05", "updateDuration": 1, @@ -117,6 +118,7 @@ const nlohmann::json CONFIG_JSON = R"( "portraitLayouts": [ "$layout:ability_form" ], + "formVisibleNotify": true, "deepLink": "ability://com.example.myapplication.fa/.MainAbility", "formConfigAbility": "ability://com.example.myapplication.fa/.MainAbility", "metaData": { @@ -893,7 +895,7 @@ HWTEST_F(BmsBundleParserTest, TestParse_2400, Function | SmallTest | Level1) { nlohmann::json errorFormsJson = CONFIG_JSON; errorFormsJson[BUNDLE_PROFILE_KEY_MODULE][BUNDLE_MODULE_PROFILE_KEY_ABILITIES]= R"( - [{ + [{ "skills": [ { "entities": [ @@ -938,7 +940,7 @@ HWTEST_F(BmsBundleParserTest, TestParse_2400, Function | SmallTest | Level1) "type": "page", "launchType": "standard" }] - + )"_json; CheckProfileForms(errorFormsJson); } @@ -1006,7 +1008,6 @@ HWTEST_F(BmsBundleParserTest, TestParse_2700, Function | SmallTest | Level1) nlohmann::json errorShortcutJson = CONFIG_JSON; errorShortcutJson[BUNDLE_PROFILE_KEY_MODULE][BUNDLE_MODULE_PROFILE_KEY_SHORTCUTS] = R"( [{ - "shortcutId": "~!@#$%^&*(){}[]:;'?<>,.|`/./+_-", "label": "~!@#$%^&*(){}[]:;'?<>,.|`/./+_-", "icon": "~!@#$%^&*(){}[]:;'?<>,.|`/./+_-", "intents": [ @@ -1033,7 +1034,7 @@ HWTEST_F(BmsBundleParserTest, TestExtractByName_0100, Function | SmallTest | Lev BundleExtractor bundleExtractor(pathStream_.str()); bool result = bundleExtractor.ExtractByName(fileInBundle, fileBuffer); - ASSERT_FALSE(result); + EXPECT_FALSE(result); } /** @@ -1050,7 +1051,7 @@ HWTEST_F(BmsBundleParserTest, TestExtractByName_0200, Function | SmallTest | Lev BundleExtractor bundleExtractor(pathStream_.str()); bool result = bundleExtractor.ExtractByName(fileInBundle, fileBuffer); - ASSERT_FALSE(result); + EXPECT_FALSE(result); } /** @@ -1073,7 +1074,7 @@ HWTEST_F(BmsBundleParserTest, TestExtractByName_0300, Function | SmallTest | Lev BundleExtractor bundleExtractor(pathStream_.str()); bool result = bundleExtractor.ExtractByName(fileInBundle, fileBuffer); - ASSERT_FALSE(result); + EXPECT_FALSE(result); } /** @@ -1096,7 +1097,7 @@ HWTEST_F(BmsBundleParserTest, TestExtractByName_0400, Function | SmallTest | Lev BundleExtractor bundleExtractor(pathStream_.str()); bool result = bundleExtractor.ExtractByName(fileInBundle, fileBuffer); - ASSERT_FALSE(result); + EXPECT_FALSE(result); } /** @@ -1116,5 +1117,5 @@ HWTEST_F(BmsBundleParserTest, TestExtractByName_0500, Function | SmallTest | Lev BundleExtractor bundleExtractor(pathStream_.str()); bool result = bundleExtractor.ExtractByName(fileInBundle, fileBuffer); - ASSERT_FALSE(result); + EXPECT_FALSE(result); } \ No newline at end of file diff --git a/services/bundlemgr/test/unittest/bms_bundle_permission_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_bundle_permission_test/BUILD.gn old mode 100644 new mode 100755 index 864e9a68c2949a1ad1b4e799df0bd27cdf3169f0..2d77307ed05a628a06ace3661cf90a0459a3c29b --- a/services/bundlemgr/test/unittest/bms_bundle_permission_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_bundle_permission_test/BUILD.gn @@ -19,7 +19,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsBundlePermissionTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${innerkits_path}/appexecfwk_base/src/ability_info.cpp", "${innerkits_path}/appexecfwk_base/src/application_info.cpp", @@ -34,6 +34,9 @@ ohos_unittest("BmsBundlePermissionTest") { "${services_path}/bundlemgr/src/installd/installd_host_impl.cpp", "${services_path}/bundlemgr/src/installd/installd_operator.cpp", "${services_path}/bundlemgr/src/installd/installd_service.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += [ @@ -66,6 +69,7 @@ ohos_unittest("BmsBundlePermissionTest") { "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] deps += bundle_install_deps diff --git a/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp index ccd86ee3e7eb5aeb8cdc5ee3d4436bbd46e28c19..a0046249e04518656f44d2538c757eae24b102ba 100644 --- a/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp @@ -843,7 +843,7 @@ bool BmsBundlePermissionTest::ConvertPermissionDef( return Permission::GrantMode::USER_GRANT; }(); permDef.availableScope = [&defPermission]() -> int { - int flag = 0; + uint flag = 0; if (std::find(defPermission.availableScope.begin(), defPermission.availableScope.end(), ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_SIGNATURE) != @@ -873,14 +873,14 @@ void BmsBundlePermissionTest::CheckPermissionDef( { Permission::PermissionDef permDef; ConvertPermissionDef(permDef, defPermission, bundlename); - ASSERT_EQ(permissionDef.permissionName, permDef.permissionName); - ASSERT_EQ(permissionDef.bundleName, bundlename); - ASSERT_EQ(permissionDef.availableScope, permDef.availableScope); - ASSERT_EQ(permissionDef.grantMode, permDef.grantMode); - ASSERT_EQ(permissionDef.labelId, permDef.labelId); - ASSERT_EQ(permissionDef.label, permDef.label); - ASSERT_EQ(permissionDef.description, permDef.description); - ASSERT_EQ(permissionDef.descriptionId, permDef.descriptionId); + EXPECT_EQ(permissionDef.permissionName, permDef.permissionName); + EXPECT_EQ(permissionDef.bundleName, bundlename); + EXPECT_EQ(permissionDef.availableScope, permDef.availableScope); + EXPECT_EQ(permissionDef.grantMode, permDef.grantMode); + EXPECT_EQ(permissionDef.labelId, permDef.labelId); + EXPECT_EQ(permissionDef.label, permDef.label); + EXPECT_EQ(permissionDef.description, permDef.description); + EXPECT_EQ(permissionDef.descriptionId, permDef.descriptionId); } void BmsBundlePermissionTest::CheckErrPermissionDef( @@ -888,14 +888,14 @@ void BmsBundlePermissionTest::CheckErrPermissionDef( { Permission::PermissionDef permDef; ConvertPermissionDef(permDef, defPermission, bundlename); - ASSERT_NE(permissionDef.permissionName, permDef.permissionName); - ASSERT_NE(permissionDef.bundleName, bundlename); - ASSERT_NE(permissionDef.availableScope, permDef.availableScope); - ASSERT_NE(permissionDef.grantMode, permDef.grantMode); - ASSERT_NE(permissionDef.labelId, permDef.labelId); - ASSERT_NE(permissionDef.label, permDef.label); - ASSERT_NE(permissionDef.description, permDef.description); - ASSERT_NE(permissionDef.descriptionId, permDef.descriptionId); + EXPECT_NE(permissionDef.permissionName, permDef.permissionName); + EXPECT_NE(permissionDef.bundleName, bundlename); + EXPECT_NE(permissionDef.availableScope, permDef.availableScope); + EXPECT_NE(permissionDef.grantMode, permDef.grantMode); + EXPECT_NE(permissionDef.labelId, permDef.labelId); + EXPECT_NE(permissionDef.label, permDef.label); + EXPECT_NE(permissionDef.description, permDef.description); + EXPECT_NE(permissionDef.descriptionId, permDef.descriptionId); } /** @@ -910,7 +910,7 @@ HWTEST_F(BmsBundlePermissionTest, HapVerify_0100, Function | SmallTest | Level0) Verify::HapVerifyResult hapVerifyResult; bool result = BundleVerifyMgr::HapVerify(HAP_FILE_PATH, hapVerifyResult); - ASSERT_EQ(result, true); + EXPECT_EQ(result, true); } /** @@ -924,7 +924,7 @@ HWTEST_F(BmsBundlePermissionTest, HapVerify_0200, Function | SmallTest | Level0) { Verify::HapVerifyResult hapVerifyResult; bool result = BundleVerifyMgr::HapVerify(HAP_FILE_PATH1, hapVerifyResult); - ASSERT_EQ(result, false); + EXPECT_EQ(result, false); } /** @@ -1011,7 +1011,7 @@ HWTEST_F(BmsBundlePermissionTest, InstallPermissions_0300, Function | SmallTest MockReqPermissionBundle(innerbundleinfo2); BundlePermissionMgr::InstallPermissions(innerbundleinfo2); auto result = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); - ASSERT_EQ(result, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result, Permission::TypePermissionState::PERMISSION_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo1); BundlePermissionMgr::UninstallPermissions(innerbundleinfo2); } @@ -1043,15 +1043,15 @@ HWTEST_F(BmsBundlePermissionTest, InstallPermissions_0400, Function | SmallTest BundlePermissionMgr::InstallPermissions(innerbundleinfo2); auto result1 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); auto result2 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); - ASSERT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); - ASSERT_EQ(result2, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result2, Permission::TypePermissionState::PERMISSION_GRANTED); InnerBundleInfo innerbundleinfo3; MockOtherReqPermissionBundle(innerbundleinfo3); BundlePermissionMgr::InstallPermissions(innerbundleinfo3); auto result3 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME_1, DEFPERMISSION_NAME_MUSIC, 1); auto result4 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME_1, DEFPERMISSION_NAME_APP, 1); - ASSERT_EQ(result3, Permission::TypePermissionState::PERMISSION_GRANTED); - ASSERT_EQ(result4, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result3, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result4, Permission::TypePermissionState::PERMISSION_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo1); BundlePermissionMgr::UninstallPermissions(innerbundleinfo2); BundlePermissionMgr::UninstallPermissions(innerbundleinfo3); @@ -1095,7 +1095,7 @@ HWTEST_F(BmsBundlePermissionTest, InstallPermissions_0700, Function | SmallTest MockReqPermissionBundle(innerbundleinfo2); BundlePermissionMgr::InstallPermissions(innerbundleinfo2); auto result = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME1, 1); - ASSERT_EQ(result, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); + EXPECT_EQ(result, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo1); BundlePermissionMgr::UninstallPermissions(innerbundleinfo2); } @@ -1123,11 +1123,11 @@ HWTEST_F(BmsBundlePermissionTest, InstallPermissions_0800, Function | SmallTest MockDefPermissionBundleUserGrant(innerbundleinfo2); BundlePermissionMgr::InstallPermissions(innerbundleinfo2); BundlePermissionMgr::GetPermissionDef(DEFPERMISSION_NAME10, permissionDef2); - ASSERT_NE(permissionDef2.label, DEF_LABEL2); - ASSERT_NE(permissionDef2.grantMode, Permission::GrantMode::USER_GRANT); + EXPECT_NE(permissionDef2.label, DEF_LABEL2); + EXPECT_NE(permissionDef2.grantMode, Permission::GrantMode::USER_GRANT); BundlePermissionMgr::GetPermissionDef(DEFPERMISSION_NAME11, permissionDef2); - ASSERT_NE(permissionDef2.label, DEF_LABEL2); - ASSERT_NE(permissionDef2.grantMode, Permission::GrantMode::USER_GRANT); + EXPECT_NE(permissionDef2.label, DEF_LABEL2); + EXPECT_NE(permissionDef2.grantMode, Permission::GrantMode::USER_GRANT); auto bundlename1 = innerbundleinfo2.GetBundleName(); BundlePermissionMgr::GetPermissionDef(DEFPERMISSION_NAME12, permissionDef2); CheckPermissionDef(DEFPERMISSION_USERGRANT3, bundlename1, permissionDef2); @@ -1199,14 +1199,14 @@ HWTEST_F(BmsBundlePermissionTest, UninstallPermissions_0200, Function | SmallTes MockReqPermissionBundle(innerbundleinfo1); BundlePermissionMgr::InstallPermissions(innerbundleinfo1); auto result = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); - ASSERT_EQ(result, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result, Permission::TypePermissionState::PERMISSION_GRANTED); auto result1 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); - ASSERT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo1); auto result2 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); - ASSERT_EQ(result2, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); + EXPECT_EQ(result2, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); auto result3 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); - ASSERT_EQ(result3, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); + EXPECT_EQ(result3, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo); BundlePermissionMgr::UninstallPermissions(innerbundleinfo1); } @@ -1289,25 +1289,25 @@ HWTEST_F(BmsBundlePermissionTest, UninstallPermissions_0400, Function | SmallTes BundlePermissionMgr::InstallPermissions(innerbundleinfo2); auto result1 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); auto result2 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); - ASSERT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); - ASSERT_EQ(result2, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result2, Permission::TypePermissionState::PERMISSION_GRANTED); InnerBundleInfo innerbundleinfo3; PermissionDef permissionDef3; MockOtherReqPermissionBundle(innerbundleinfo3); BundlePermissionMgr::InstallPermissions(innerbundleinfo3); auto result3 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME_1, DEFPERMISSION_NAME_APP, 1); auto result4 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME_1, DEFPERMISSION_NAME_MUSIC, 1); - ASSERT_EQ(result3, Permission::TypePermissionState::PERMISSION_GRANTED); - ASSERT_EQ(result4, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result3, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result4, Permission::TypePermissionState::PERMISSION_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo2); auto result5 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); auto result6 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); auto result7 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME_1, DEFPERMISSION_NAME_APP, 1); auto result8 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME_1, DEFPERMISSION_NAME_MUSIC, 1); - ASSERT_EQ(result5, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); - ASSERT_EQ(result6, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); - ASSERT_EQ(result7, Permission::TypePermissionState::PERMISSION_GRANTED); - ASSERT_EQ(result8, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result5, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); + EXPECT_EQ(result6, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); + EXPECT_EQ(result7, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result8, Permission::TypePermissionState::PERMISSION_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo1); BundlePermissionMgr::UninstallPermissions(innerbundleinfo2); BundlePermissionMgr::UninstallPermissions(innerbundleinfo3); @@ -1378,9 +1378,9 @@ HWTEST_F(BmsBundlePermissionTest, UninstallPermissions_0600, Function | SmallTes MockReqPermissionBundle(innerbundleinfo2); BundlePermissionMgr::InstallPermissions(innerbundleinfo2); auto result1 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); - ASSERT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); auto result2 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); - ASSERT_EQ(result2, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result2, Permission::TypePermissionState::PERMISSION_GRANTED); InnerBundleInfo innerbundleinfo3; PermissionDef permissionDef1; MockNoDefPermissionBundle(innerbundleinfo3); @@ -1394,9 +1394,9 @@ HWTEST_F(BmsBundlePermissionTest, UninstallPermissions_0600, Function | SmallTes CheckErrPermissionDef(DEFPERMISSION_SYSTEM3, bundlename1, permissionDef1); BundlePermissionMgr::UninstallPermissions(innerbundleinfo3); auto result3 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); - ASSERT_EQ(result3, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result3, Permission::TypePermissionState::PERMISSION_GRANTED); auto result4 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); - ASSERT_EQ(result4, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result4, Permission::TypePermissionState::PERMISSION_GRANTED); BundlePermissionMgr::UninstallPermissions(innerbundleinfo); BundlePermissionMgr::UninstallPermissions(innerbundleinfo2); BundlePermissionMgr::UninstallPermissions(innerbundleinfo3); @@ -1433,7 +1433,7 @@ HWTEST_F(BmsBundlePermissionTest, UpdatePermissions_0100, Function | SmallTest | CheckPermissionDef(DEFPERMISSION_SAME2, bundlename1, permissionDef2); BundlePermissionMgr::GetPermissionDef(DEFPERMISSION_NAME18, permissionDef2); CheckPermissionDef(DEFPERMISSION_SAME3, bundlename1, permissionDef2); - ASSERT_EQ(result, true); + EXPECT_EQ(result, true); } /** @@ -1449,7 +1449,7 @@ HWTEST_F(BmsBundlePermissionTest, CheckCallingPermission_0100, Function | SmallT MockDefPermissionBundleSystemGrant(innerbundleinfo); std::string permissionName = DEFPERMISSION_NAME1; ErrCode result = BundlePermissionMgr::CheckCallingPermission(permissionName); - ASSERT_EQ(result, true); + EXPECT_EQ(result, true); } /** @@ -1479,8 +1479,8 @@ HWTEST_F(BmsBundlePermissionTest, VerifyPermission_0100, Function | SmallTest | BundlePermissionMgr::InstallPermissions(innerbundleinfo2); auto result = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_EMAIL, 1); auto result1 = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, DEFPERMISSION_NAME_WECHAT, 1); - ASSERT_EQ(result, Permission::TypePermissionState::PERMISSION_GRANTED); - ASSERT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result, Permission::TypePermissionState::PERMISSION_GRANTED); + EXPECT_EQ(result1, Permission::TypePermissionState::PERMISSION_GRANTED); } /** @@ -1509,7 +1509,7 @@ HWTEST_F(BmsBundlePermissionTest, VerifyPermission_0200, Function | SmallTest | MockReqPermissionBundle(innerbundleinfo2); BundlePermissionMgr::InstallPermissions(innerbundleinfo2); auto result = BundlePermissionMgr::VerifyPermission(MOCK_REQPERMISSION_NAME, "error", 1); - ASSERT_EQ(result, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); + EXPECT_EQ(result, Permission::TypePermissionState::PERMISSION_NOT_GRANTED); } /** @@ -1528,7 +1528,7 @@ HWTEST_F(BmsBundlePermissionTest, GetPermissionDef_0100, Function | SmallTest | std::string permissionName = DEFPERMISSION_NAME1; ErrCode result = BundlePermissionMgr::GetPermissionDef(permissionName, permdef); CheckPermissionDef(DEFPERMISSION_SYSTEM1, bundlename, permdef); - ASSERT_EQ(result, true); + EXPECT_EQ(result, true); } /** @@ -1547,12 +1547,12 @@ HWTEST_F(BmsBundlePermissionTest, GetPermissionDef_0200, Function | SmallTest | std::string permissionName1 = DEFPERMISSION_NAME1; ErrCode result1 = BundlePermissionMgr::GetPermissionDef(permissionName1, permdef1); CheckPermissionDef(DEFPERMISSION_SYSTEM1, bundlename, permdef1); - ASSERT_EQ(result1, true); + EXPECT_EQ(result1, true); PermissionDef permdef2; std::string permissionName2 = DEFPERMISSION_NAME2; ErrCode result2 = BundlePermissionMgr::GetPermissionDef(permissionName2, permdef2); CheckPermissionDef(DEFPERMISSION_SYSTEM2, bundlename, permdef2); - ASSERT_EQ(result2, true); + EXPECT_EQ(result2, true); } /** @@ -1574,32 +1574,32 @@ HWTEST_F(BmsBundlePermissionTest, GetPermissionDef_0300, Function | SmallTest | std::string permissionName1 = DEFPERMISSION_NAME1; ErrCode result1 = BundlePermissionMgr::GetPermissionDef(permissionName1, permdef); CheckPermissionDef(DEFPERMISSION_SYSTEM1, bundlename, permdef); - ASSERT_EQ(result1, true); + EXPECT_EQ(result1, true); PermissionDef permdef1; std::string permissionName2 = DEFPERMISSION_NAME2; ErrCode result2 = BundlePermissionMgr::GetPermissionDef(permissionName2, permdef1); CheckPermissionDef(DEFPERMISSION_SYSTEM2, bundlename, permdef1); - ASSERT_EQ(result2, true); + EXPECT_EQ(result2, true); PermissionDef permdef2; std::string permissionName3 = DEFPERMISSION_NAME3; ErrCode result3 = BundlePermissionMgr::GetPermissionDef(permissionName3, permdef2); CheckPermissionDef(DEFPERMISSION_SYSTEM3, bundlename, permdef2); - ASSERT_EQ(result3, true); + EXPECT_EQ(result3, true); PermissionDef permdef3; std::string permissionName4 = DEFPERMISSION_NAME16; ErrCode result4 = BundlePermissionMgr::GetPermissionDef(permissionName4, permdef3); CheckPermissionDef(DEFPERMISSION_SAME1, bundlename1, permdef3); - ASSERT_EQ(result4, true); + EXPECT_EQ(result4, true); PermissionDef permdef4; std::string permissionName5 = DEFPERMISSION_NAME17; ErrCode result5 = BundlePermissionMgr::GetPermissionDef(permissionName5, permdef4); CheckPermissionDef(DEFPERMISSION_SAME2, bundlename1, permdef4); - ASSERT_EQ(result5, true); + EXPECT_EQ(result5, true); PermissionDef permdef5; std::string permissionName6 = DEFPERMISSION_NAME18; ErrCode result6 = BundlePermissionMgr::GetPermissionDef(permissionName6, permdef5); CheckPermissionDef(DEFPERMISSION_SAME3, bundlename1, permdef5); - ASSERT_EQ(result6, true); + EXPECT_EQ(result6, true); } /** @@ -1618,10 +1618,10 @@ HWTEST_F(BmsBundlePermissionTest, GetPermissionDef_0400, Function | SmallTest | std::string permissionName = "1"; ErrCode result = BundlePermissionMgr::GetPermissionDef(permissionName, permdef); CheckErrPermissionDef(DEFPERMISSION_SYSTEM1, bundlename, permdef); - ASSERT_NE(permdef.permissionName, DEFPERMISSION_NAME1); - ASSERT_NE(permdef.permissionName, DEFPERMISSION_NAME2); - ASSERT_NE(permdef.permissionName, DEFPERMISSION_NAME3); - ASSERT_EQ(result, false); + EXPECT_NE(permdef.permissionName, DEFPERMISSION_NAME1); + EXPECT_NE(permdef.permissionName, DEFPERMISSION_NAME2); + EXPECT_NE(permdef.permissionName, DEFPERMISSION_NAME3); + EXPECT_NE(result, true); } /** @@ -1640,10 +1640,10 @@ HWTEST_F(BmsBundlePermissionTest, GetPermissionDef_0500, Function | SmallTest | std::string permissionName = ""; ErrCode result = BundlePermissionMgr::GetPermissionDef(permissionName, permdef); CheckErrPermissionDef(DEFPERMISSION_SYSTEM1, bundlename, permdef); - ASSERT_NE(permdef.permissionName, DEFPERMISSION_NAME1); - ASSERT_NE(permdef.permissionName, DEFPERMISSION_NAME2); - ASSERT_NE(permdef.permissionName, DEFPERMISSION_NAME3); - ASSERT_EQ(result, false); + EXPECT_NE(permdef.permissionName, DEFPERMISSION_NAME1); + EXPECT_NE(permdef.permissionName, DEFPERMISSION_NAME2); + EXPECT_NE(permdef.permissionName, DEFPERMISSION_NAME3); + EXPECT_EQ(result, false); } /** @@ -1660,7 +1660,7 @@ HWTEST_F(BmsBundlePermissionTest, CanRequestPermission_0100, Function | SmallTes std::string permissionName = DEFPERMISSION_NAME3; int userId = '1'; ErrCode result = BundlePermissionMgr::CanRequestPermission(innerbundleinfo.GetBundleName(), permissionName, userId); - ASSERT_EQ(result, 0); + EXPECT_EQ(result, 0); } /** @@ -1678,5 +1678,5 @@ HWTEST_F(BmsBundlePermissionTest, RequestPermissionFromUser_0100, Function | Sma int userId = '1'; ErrCode result = BundlePermissionMgr::RequestPermissionFromUser(innerbundleinfo.GetBundleName(), permissionName, userId); - ASSERT_EQ(result, true); + EXPECT_EQ(result, true); } diff --git a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/BUILD.gn old mode 100644 new mode 100755 index 93467df52cd41c012e54ecf12e544656538ac46b..2e1a6d40b72b1c2846193a5948a3441ad62b54e3 --- a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/BUILD.gn @@ -24,7 +24,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsBundleUninstallerTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${services_path}/bundlemgr/src/bundle_data_mgr.cpp", "${services_path}/bundlemgr/src/bundle_data_storage_database.cpp", @@ -36,6 +36,9 @@ ohos_unittest("BmsBundleUninstallerTest") { "${services_path}/bundlemgr/src/installd/installd_host_impl.cpp", "${services_path}/bundlemgr/src/installd/installd_operator.cpp", "${services_path}/bundlemgr/src/installd/installd_service.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += [ @@ -66,6 +69,7 @@ ohos_unittest("BmsBundleUninstallerTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp index 56d6dedee8496e8835259d0c94e3ff03e4afb97e..4de4e6cd5921e536244eccdee2d361815f515894 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp @@ -100,13 +100,13 @@ void BmsBundleUninstallerTest::SetUpTestCase() { if (access(ROOT_DIR.c_str(), F_OK) != 0) { bool result = OHOS::ForceCreateDirectory(ROOT_DIR); - ASSERT_TRUE(result); + EXPECT_TRUE(result); } if (chown(ROOT_DIR.c_str(), ROOT_UID, ROOT_UID) != 0) { - ASSERT_TRUE(false); + EXPECT_TRUE(false); } if (chmod(ROOT_DIR.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { - ASSERT_TRUE(false); + EXPECT_TRUE(false); } } @@ -194,46 +194,46 @@ ErrCode BmsBundleUninstallerTest::UninstallModule(const std::string &bundleName, void BmsBundleUninstallerTest::CheckFileExist() const { int bundleDataExist = access(BUNDLE_DATA_DIR.c_str(), F_OK); - ASSERT_EQ(bundleDataExist, 0); + EXPECT_EQ(bundleDataExist, 0); int bundleCodeExist = access(BUNDLE_CODE_DIR.c_str(), F_OK); - ASSERT_EQ(bundleCodeExist, 0); + EXPECT_EQ(bundleCodeExist, 0); } void BmsBundleUninstallerTest::CheckModuleFileExist() const { int moduleDataExist = access(MODULE_DATA_DIR.c_str(), F_OK); - ASSERT_EQ(moduleDataExist, 0); + EXPECT_EQ(moduleDataExist, 0); int moduleCodeExist = access(MODULE_CODE_DIR.c_str(), F_OK); - ASSERT_EQ(moduleCodeExist, 0); + EXPECT_EQ(moduleCodeExist, 0); } void BmsBundleUninstallerTest::CheckModuleFileExist1() const { int moduleDataExist1 = access(MODULE_DATA_DIR1.c_str(), F_OK); - ASSERT_EQ(moduleDataExist1, 0); + EXPECT_EQ(moduleDataExist1, 0); int moduleCodeExist1 = access(MODULE_CODE_DIR1.c_str(), F_OK); - ASSERT_EQ(moduleCodeExist1, 0); + EXPECT_EQ(moduleCodeExist1, 0); } void BmsBundleUninstallerTest::CheckFileNonExist() const { int bundleDataExist = access(BUNDLE_DATA_DIR.c_str(), F_OK); - ASSERT_NE(bundleDataExist, 0); + EXPECT_NE(bundleDataExist, 0); int bundleCodeExist = access(BUNDLE_CODE_DIR.c_str(), F_OK); - ASSERT_NE(bundleCodeExist, 0); + EXPECT_NE(bundleCodeExist, 0); } void BmsBundleUninstallerTest::CheckModuleFileNonExist() const { int moduleDataExist = access(MODULE_DATA_DIR.c_str(), F_OK); - ASSERT_NE(moduleDataExist, 0); + EXPECT_NE(moduleDataExist, 0); int moduleCodeExist = access(MODULE_CODE_DIR.c_str(), F_OK); - ASSERT_NE(moduleCodeExist, 0); + EXPECT_NE(moduleCodeExist, 0); } void BmsBundleUninstallerTest::StopInstalldService() const @@ -267,22 +267,22 @@ void BmsBundleUninstallerTest::StopBundleService() void BmsBundleUninstallerTest::CheckBundleInfoExist() const { - ASSERT_NE(bundleMgrService_, nullptr); + EXPECT_NE(bundleMgrService_, nullptr); auto dataMgr = bundleMgrService_->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo info; bool isBundleExist = dataMgr->GetBundleInfo(BUNDLE_NAME, BundleFlag::GET_BUNDLE_DEFAULT, info); - ASSERT_TRUE(isBundleExist); + EXPECT_TRUE(isBundleExist); } void BmsBundleUninstallerTest::CheckBundleInfoNonExist() const { - ASSERT_NE(bundleMgrService_, nullptr); + EXPECT_NE(bundleMgrService_, nullptr); auto dataMgr = bundleMgrService_->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo info; bool isBundleExist = dataMgr->GetBundleInfo(BUNDLE_NAME, BundleFlag::GET_BUNDLE_DEFAULT, info); - ASSERT_FALSE(isBundleExist); + EXPECT_FALSE(isBundleExist); } const std::shared_ptr BmsBundleUninstallerTest::GetBundleMgrService() const @@ -308,7 +308,7 @@ void BmsBundleUninstallerTest::ClearBundleInfoInDb() applicationInfo.bundleName = BUNDLE_NAME; innerBundleInfo.SetBaseApplicationInfo(applicationInfo); bool result = dataStorage->DeleteStorageBundleInfo(Constants::CURRENT_DEVICE_ID, innerBundleInfo); - ASSERT_TRUE(result) << "the bundle info in db clear fail: " << BUNDLE_NAME; + EXPECT_TRUE(result) << "the bundle info in db clear fail: " << BUNDLE_NAME; } void BmsBundleUninstallerTest::DeleteInstallFiles() @@ -329,12 +329,12 @@ void BmsBundleUninstallerTest::DeleteInstallFiles() HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0100, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckBundleInfoExist(); CheckFileExist(); ErrCode uninstallResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); CheckFileNonExist(); CheckBundleInfoNonExist(); } @@ -373,19 +373,19 @@ HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0300, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0400, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(); CheckBundleInfoExist(); StopBundleService(); ErrCode secondResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(secondResult, ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR); + EXPECT_EQ(secondResult, ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR); CheckFileExist(); StartBundleService(); CheckBundleInfoExist(); ErrCode thirdResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(thirdResult, ERR_OK); + EXPECT_EQ(thirdResult, ERR_OK); CheckFileNonExist(); CheckBundleInfoNonExist(); } @@ -399,13 +399,13 @@ HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0400, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0500, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(); CheckBundleInfoExist(); StopInstalldService(); ErrCode uninstallResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(uninstallResult, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); + EXPECT_EQ(uninstallResult, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); CheckFileExist(); StartInstalldService(); @@ -422,16 +422,16 @@ HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0500, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0600, Function | SmallTest | Level1) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(); CheckBundleInfoExist(); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; auto bms = GetBundleMgrService(); - ASSERT_NE(bms, nullptr); + EXPECT_NE(bms, nullptr); auto installer = bms->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); bool result = installer->Uninstall(BUNDLE_NAME, installParam, nullptr); EXPECT_FALSE(result); @@ -450,14 +450,14 @@ HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0600, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0700, Function | SmallTest | Level0) { auto installer = std::make_unique(BUNDLE_FILE_PATH); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); bool installResult = installer->InstallSystemBundle(Constants::AppType::SYSTEM_APP); - ASSERT_EQ(installResult, true); + EXPECT_EQ(installResult, true); CheckFileExist(); CheckBundleInfoExist(); ErrCode uninstallResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR); + EXPECT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR); CheckFileExist(); CheckBundleInfoExist(); DeleteInstallFiles(); @@ -472,12 +472,12 @@ HWTEST_F(BmsBundleUninstallerTest, Bundle_Uninstall_0700, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0100, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckBundleInfoExist(); CheckFileExist(); ErrCode uninstallResult = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); CheckFileNonExist(); CheckBundleInfoNonExist(); } @@ -516,19 +516,19 @@ HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0300, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0400, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(); CheckBundleInfoExist(); StopBundleService(); ErrCode secondResult = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(secondResult, ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR); + EXPECT_EQ(secondResult, ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR); CheckFileExist(); StartBundleService(); CheckBundleInfoExist(); ErrCode thirdResult = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(thirdResult, ERR_OK); + EXPECT_EQ(thirdResult, ERR_OK); CheckFileNonExist(); CheckBundleInfoNonExist(); } @@ -542,13 +542,13 @@ HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0400, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0500, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(); CheckBundleInfoExist(); StopInstalldService(); ErrCode uninstallResult = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(uninstallResult, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); + EXPECT_EQ(uninstallResult, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); CheckFileExist(); StartInstalldService(); @@ -565,16 +565,16 @@ HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0500, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0600, Function | SmallTest | Level1) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(); CheckBundleInfoExist(); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; auto bms = GetBundleMgrService(); - ASSERT_NE(bms, nullptr); + EXPECT_NE(bms, nullptr); auto installer = bms->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); bool result = installer->Uninstall(BUNDLE_NAME, MODULE_PACKAGE, installParam, nullptr); EXPECT_FALSE(result); @@ -593,14 +593,14 @@ HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0600, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0700, Function | SmallTest | Level0) { auto installer = std::make_unique(BUNDLE_FILE_PATH); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); bool installResult = installer->InstallSystemBundle(Constants::AppType::SYSTEM_APP); - ASSERT_EQ(installResult, true); + EXPECT_EQ(installResult, true); CheckFileExist(); CheckBundleInfoExist(); ErrCode uninstallResult = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR); + EXPECT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR); CheckFileExist(); CheckBundleInfoExist(); DeleteInstallFiles(); @@ -615,16 +615,16 @@ HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0700, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0800, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); ErrCode installResult1 = InstallBundle(BUNDLE_FILE_PATH1); - ASSERT_EQ(installResult1, ERR_OK); + EXPECT_EQ(installResult1, ERR_OK); CheckBundleInfoExist(); CheckFileExist(); CheckModuleFileExist(); CheckModuleFileExist1(); ErrCode uninstallResult = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); CheckModuleFileNonExist(); CheckModuleFileExist1(); CheckBundleInfoExist(); @@ -640,18 +640,18 @@ HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0800, Function | SmallTest | HWTEST_F(BmsBundleUninstallerTest, Module_Uninstall_0900, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_PATH); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); ErrCode installResult1 = InstallBundle(BUNDLE_FILE_PATH1); - ASSERT_EQ(installResult1, ERR_OK); + EXPECT_EQ(installResult1, ERR_OK); CheckBundleInfoExist(); CheckFileExist(); CheckModuleFileExist(); CheckModuleFileExist1(); ErrCode uninstallResult = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); ErrCode uninstallResult1 = UninstallModule(BUNDLE_NAME, MODULE_PACKAGE1); - ASSERT_EQ(uninstallResult1, ERR_OK); + EXPECT_EQ(uninstallResult1, ERR_OK); CheckFileNonExist(); CheckBundleInfoNonExist(); DeleteInstallFiles(); diff --git a/services/bundlemgr/test/unittest/bms_bundle_updater_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_bundle_updater_test/BUILD.gn old mode 100644 new mode 100755 index 3b86be9ea797ff7dc06a8156728a4149c05f09b0..88c04eceb29d8a6921406458fb6bab17ed407f83 --- a/services/bundlemgr/test/unittest/bms_bundle_updater_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_bundle_updater_test/BUILD.gn @@ -27,7 +27,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsBundleUpdaterTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${services_path}/bundlemgr/src/bundle_data_mgr.cpp", "${services_path}/bundlemgr/src/bundle_data_storage_database.cpp", @@ -39,6 +39,9 @@ ohos_unittest("BmsBundleUpdaterTest") { "${services_path}/bundlemgr/src/installd/installd_host_impl.cpp", "${services_path}/bundlemgr/src/installd/installd_operator.cpp", "${services_path}/bundlemgr/src/installd/installd_service.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += [ @@ -70,6 +73,7 @@ ohos_unittest("BmsBundleUpdaterTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp index b66b206385e387692f861b4449218de5ac22e094..c305f3712c39bd35016e14abe7f70d4f75b3f619 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp @@ -89,13 +89,13 @@ void BmsBundleUpdaterTest::SetUpTestCase() { if (access(ROOT_DIR.c_str(), F_OK) != 0) { bool result = OHOS::ForceCreateDirectory(ROOT_DIR); - ASSERT_TRUE(result) << "fail to create root dir"; + EXPECT_TRUE(result) << "fail to create root dir"; } if (chown(ROOT_DIR.c_str(), ROOT_UID, ROOT_UID) != 0) { - ASSERT_TRUE(false) << "fail to change root dir own ship"; + EXPECT_TRUE(false) << "fail to change root dir own ship"; } if (chmod(ROOT_DIR.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { - ASSERT_TRUE(false) << "fail to change root dir mode"; + EXPECT_TRUE(false) << "fail to change root dir mode"; } } @@ -289,7 +289,7 @@ bool BmsBundleUpdaterTest::CheckApplicationInfo() const HWTEST_F(BmsBundleUpdaterTest, Update_0100, Function | SmallTest | Level2) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CommonTool tool; long codeDirFirstCreateTime = tool.GetFileBuildTime(BUNDLE_CODE_DIR.c_str()); long dataDirFirstCreateTime = tool.GetFileBuildTime(BUNDLE_DATA_DIR.c_str()); @@ -298,12 +298,12 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0100, Function | SmallTest | Level2) std::this_thread::sleep_for(SLEEP_TIME); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + V2_BUNDLE, true); - ASSERT_EQ(updateResult, ERR_OK); + EXPECT_EQ(updateResult, ERR_OK); long codeDirSecondCreateTime = tool.GetFileBuildTime(BUNDLE_CODE_DIR.c_str()); long dataDirSecondCreateTime = tool.GetFileBuildTime(BUNDLE_DATA_DIR.c_str()); - ASSERT_EQ(dataDirFirstCreateTime, dataDirSecondCreateTime); - ASSERT_NE(codeDirFirstCreateTime, codeDirSecondCreateTime); + EXPECT_EQ(dataDirFirstCreateTime, dataDirSecondCreateTime); + EXPECT_NE(codeDirFirstCreateTime, codeDirSecondCreateTime); bool isExist = CheckBundleInfo(VERSION_2, true); EXPECT_TRUE(isExist); @@ -318,10 +318,10 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0100, Function | SmallTest | Level2) HWTEST_F(BmsBundleUpdaterTest, Update_0200, Function | SmallTest | Level1) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V2_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + V3_BUNDLE); - ASSERT_EQ(updateResult, ERR_OK); + EXPECT_EQ(updateResult, ERR_OK); CheckFileExist(); bool result = CheckBundleInfo(VERSION_3, true); @@ -337,7 +337,7 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0200, Function | SmallTest | Level1) HWTEST_F(BmsBundleUpdaterTest, Update_0300, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); ErrCode updateResult = UpdateBundle(""); EXPECT_EQ(updateResult, ERR_APPEXECFWK_INSTALL_FILE_PATH_INVALID); @@ -352,7 +352,7 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0300, Function | SmallTest | Level0) HWTEST_F(BmsBundleUpdaterTest, Update_0400, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + ERROR_BUNDLE_NAME); EXPECT_EQ(updateResult, ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME); @@ -367,7 +367,7 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0400, Function | SmallTest | Level0) HWTEST_F(BmsBundleUpdaterTest, Update_0500, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + ERROR_FORMART_BUNDLE); EXPECT_EQ(updateResult, ERR_APPEXECFWK_PARSE_NO_PROFILE); @@ -382,7 +382,7 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0500, Function | SmallTest | Level0) HWTEST_F(BmsBundleUpdaterTest, Update_0600, Function | SmallTest | Level0) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V2_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + V1_BUNDLE); EXPECT_EQ(updateResult, ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE); @@ -398,23 +398,23 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0600, Function | SmallTest | Level0) HWTEST_F(BmsBundleUpdaterTest, Update_0700, Function | SmallTest | Level1) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); StopInstalldService(); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + V3_BUNDLE); - ASSERT_EQ(updateResult, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); + EXPECT_EQ(updateResult, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); BundleInfo info; auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool isInfoExist = dataMgr->GetBundleInfo(BUNDLE_NAME, BundleFlag::GET_BUNDLE_DEFAULT, info); - ASSERT_TRUE(isInfoExist); - ASSERT_EQ(info.versionCode, VERSION_1); + EXPECT_TRUE(isInfoExist); + EXPECT_EQ(info.versionCode, VERSION_1); StartInstalldService(); updateResult = UpdateBundle(BUNDLE_FILE_DIR + V3_BUNDLE); - ASSERT_EQ(updateResult, ERR_OK); - ASSERT_EQ(info.versionCode, VERSION_1); + EXPECT_EQ(updateResult, ERR_OK); + EXPECT_EQ(info.versionCode, VERSION_1); CheckFileExist(); } @@ -428,32 +428,32 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0700, Function | SmallTest | Level1) HWTEST_F(BmsBundleUpdaterTest, Update_0800, Function | SmallTest | Level1) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); StopBundleService(); DelayedSingleton::DestroyInstance(); sptr installer = new (std::nothrow) BundleInstallerHost(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); installer->Init(); sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::REPLACE_EXISTING; installer->Install(BUNDLE_FILE_DIR + V3_BUNDLE, installParam, receiver); ErrCode result = receiver->GetResultCode(); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR); DelayedSingleton::GetInstance()->OnStart(); BundleInfo info; auto dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool isInfoExist = dataMgr->GetBundleInfo(BUNDLE_NAME, BundleFlag::GET_BUNDLE_DEFAULT, info); - ASSERT_TRUE(isInfoExist); - ASSERT_EQ(info.versionCode, VERSION_1); + EXPECT_TRUE(isInfoExist); + EXPECT_EQ(info.versionCode, VERSION_1); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + V3_BUNDLE); - ASSERT_EQ(updateResult, ERR_OK); + EXPECT_EQ(updateResult, ERR_OK); CheckFileExist(); } @@ -466,13 +466,13 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0800, Function | SmallTest | Level1) HWTEST_F(BmsBundleUpdaterTest, Update_0900, Function | SmallTest | Level2) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CommonTool tool; long codeDirFirstCreateTime = tool.GetFileBuildTime(BUNDLE_CODE_DIR.c_str()); long dataDirFirstCreateTime = tool.GetFileBuildTime(BUNDLE_DATA_DIR.c_str()); auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_FALSE(!installer); + EXPECT_FALSE(!installer); InstallParam installParam; installParam.installFlag = InstallFlag::REPLACE_EXISTING; installer->Install(BUNDLE_FILE_DIR + V2_BUNDLE, installParam, nullptr); @@ -482,8 +482,8 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0900, Function | SmallTest | Level2) long codeDirSecondCreateTime = tool.GetFileBuildTime(BUNDLE_CODE_DIR.c_str()); long dataDirSecondCreateTime = tool.GetFileBuildTime(BUNDLE_DATA_DIR.c_str()); - ASSERT_EQ(dataDirFirstCreateTime, dataDirSecondCreateTime); - ASSERT_EQ(codeDirFirstCreateTime, codeDirSecondCreateTime); + EXPECT_EQ(dataDirFirstCreateTime, dataDirSecondCreateTime); + EXPECT_EQ(codeDirFirstCreateTime, codeDirSecondCreateTime); bool isExist = CheckBundleInfo(VERSION_1, true); EXPECT_TRUE(isExist); @@ -498,7 +498,7 @@ HWTEST_F(BmsBundleUpdaterTest, Update_0900, Function | SmallTest | Level2) HWTEST_F(BmsBundleUpdaterTest, Update_1000, Function | SmallTest | Level2) { ErrCode installResult = InstallBundle(BUNDLE_FILE_DIR + V1_BUNDLE); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CommonTool tool; long codeDirFirstCreateTime = tool.GetFileBuildTime(BUNDLE_CODE_DIR.c_str()); long dataDirFirstCreateTime = tool.GetFileBuildTime(BUNDLE_DATA_DIR.c_str()); @@ -507,12 +507,12 @@ HWTEST_F(BmsBundleUpdaterTest, Update_1000, Function | SmallTest | Level2) std::this_thread::sleep_for(SLEEP_TIME); ErrCode updateResult = UpdateBundle(BUNDLE_FILE_DIR + V2_BUNDLE); - ASSERT_EQ(updateResult, ERR_OK); + EXPECT_EQ(updateResult, ERR_OK); long codeDirSecondCreateTime = tool.GetFileBuildTime(BUNDLE_CODE_DIR.c_str()); long dataDirSecondCreateTime = tool.GetFileBuildTime(BUNDLE_DATA_DIR.c_str()); - ASSERT_EQ(dataDirFirstCreateTime, dataDirSecondCreateTime); - ASSERT_NE(codeDirFirstCreateTime, codeDirSecondCreateTime); + EXPECT_EQ(dataDirFirstCreateTime, dataDirSecondCreateTime); + EXPECT_NE(codeDirFirstCreateTime, codeDirSecondCreateTime); bool isExist = CheckBundleInfo(VERSION_2, true); EXPECT_TRUE(isExist); @@ -520,12 +520,12 @@ HWTEST_F(BmsBundleUpdaterTest, Update_1000, Function | SmallTest | Level2) std::this_thread::sleep_for(SLEEP_TIME); updateResult = UpdateBundle(BUNDLE_FILE_DIR + V3_BUNDLE); - ASSERT_EQ(updateResult, ERR_OK); + EXPECT_EQ(updateResult, ERR_OK); long codeDirThirdCreateTime = tool.GetFileBuildTime(BUNDLE_CODE_DIR.c_str()); long dataDirThirdCreateTime = tool.GetFileBuildTime(BUNDLE_DATA_DIR.c_str()); - ASSERT_EQ(dataDirSecondCreateTime, dataDirThirdCreateTime); - ASSERT_NE(codeDirSecondCreateTime, codeDirThirdCreateTime); + EXPECT_EQ(dataDirSecondCreateTime, dataDirThirdCreateTime); + EXPECT_NE(codeDirSecondCreateTime, codeDirThirdCreateTime); isExist = CheckBundleInfo(VERSION_3, true); EXPECT_TRUE(isExist); diff --git a/services/bundlemgr/test/unittest/bms_data_mgr_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_data_mgr_test/BUILD.gn old mode 100644 new mode 100755 index d8f52fbec575c00dd4c87278ecc1daf3f445ee4b..52e14c4888ada354f432e2a3222fd50a6df6260a --- a/services/bundlemgr/test/unittest/bms_data_mgr_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_data_mgr_test/BUILD.gn @@ -16,11 +16,15 @@ import("//foundation/appexecfwk/standard/appexecfwk.gni") import( "//foundation/appexecfwk/standard/services/bundlemgr/appexecfwk_bundlemgr.gni") +config("private_config") { + include_dirs = [ "${services_path}/bundlemgr/test/mock/include" ] +} + module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsDataMgrTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${innerkits_path}/appexecfwk_base/src/ability_info.cpp", "${innerkits_path}/appexecfwk_base/src/application_info.cpp", @@ -28,7 +32,19 @@ ohos_unittest("BmsDataMgrTest") { "${innerkits_path}/appexecfwk_base/src/element_name.cpp", "${services_path}/bundlemgr/src/bundle_data_mgr.cpp", "${services_path}/bundlemgr/src/bundle_data_storage_database.cpp", + "${services_path}/bundlemgr/src/bundle_mgr_host_impl.cpp", + "${services_path}/bundlemgr/src/bundle_mgr_service.cpp", + "${services_path}/bundlemgr/src/bundle_mgr_service_event_handler.cpp", + "${services_path}/bundlemgr/src/bundle_scanner.cpp", "${services_path}/bundlemgr/src/bundle_status_callback_death_recipient.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", + ] + + sources += [ + "${services_path}/bundlemgr/test/mock/src/mock_status_receiver.cpp", + "${services_path}/bundlemgr/test/mock/src/system_ability_helper.cpp", ] sources += bundle_install_sources @@ -50,16 +66,21 @@ ohos_unittest("BmsDataMgrTest") { "${libs_path}/libeventhandler:libeventhandler_target", "${services_path}/bundlemgr:bundle_parser", "${services_path}/bundlemgr:parser_common", + "//base/security/appverify/interfaces/innerkits/appverify:libhapverify", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", ] deps += bundle_install_deps external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp b/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp index f22beefdb4dc6669a6098a45573f92f98efa942d..f276ed52dc02fa2306074dac2da6d27263a9a043 100755 --- a/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp +++ b/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp @@ -122,7 +122,7 @@ const std::shared_ptr BmsDataMgrTest::GetDataMgr() const HWTEST_F(BmsDataMgrTest, UpdateInstallState_0100, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_FAIL); EXPECT_TRUE(ret1); @@ -138,7 +138,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0100, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0200, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UPDATING_START); @@ -158,7 +158,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0200, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0300, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UPDATING_START); @@ -180,7 +180,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0300, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0400, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_START); @@ -200,7 +200,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0400, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0500, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_START); @@ -220,7 +220,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0500, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0600, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); EXPECT_TRUE(ret1); @@ -237,7 +237,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0600, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0700, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_START); EXPECT_TRUE(ret1); @@ -254,7 +254,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0700, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0800, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_SUCCESS); EXPECT_TRUE(ret1); @@ -271,7 +271,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0800, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_0900, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_FAIL); EXPECT_TRUE(ret1); @@ -288,7 +288,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_0900, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1000, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UPDATING_START); EXPECT_TRUE(ret1); @@ -305,7 +305,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1000, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1100, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UPDATING_SUCCESS); EXPECT_TRUE(ret1); @@ -322,7 +322,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1100, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1200, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UPDATING_FAIL); EXPECT_TRUE(ret1); @@ -339,7 +339,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1200, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1300, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); @@ -359,7 +359,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1300, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1400, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); @@ -379,7 +379,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1400, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1500, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_FAIL); @@ -399,7 +399,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1500, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1600, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_SUCCESS); @@ -419,7 +419,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1600, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1700, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UNINSTALL_FAIL); @@ -439,7 +439,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1700, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1800, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UPDATING_FAIL); @@ -459,7 +459,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1800, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_1900, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::UPDATING_SUCCESS); @@ -479,7 +479,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_1900, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, UpdateInstallState_2000, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState("", InstallState::INSTALL_START); EXPECT_FALSE(ret1); } @@ -493,7 +493,7 @@ HWTEST_F(BmsDataMgrTest, UpdateInstallState_2000, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, LoadDataFromPersistentStorage_0100, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->LoadDataFromPersistentStorage(); EXPECT_FALSE(ret1); @@ -532,7 +532,7 @@ HWTEST_F(BmsDataMgrTest, AddBundleInfo_0100, Function | SmallTest | Level0) info.SetBaseBundleInfo(bundleInfo); info.SetBaseApplicationInfo(applicationInfo); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); InnerBundleInfo info1; bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); @@ -577,7 +577,7 @@ HWTEST_F(BmsDataMgrTest, AddBundleInfo_0200, Function | SmallTest | Level0) info2.SetBaseBundleInfo(bundleInfo2); info2.SetBaseApplicationInfo(applicationInfo2); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->AddInnerBundleInfo(BUNDLE_NAME, info1); @@ -610,7 +610,7 @@ HWTEST_F(BmsDataMgrTest, AddBundleInfo_0200, Function | SmallTest | Level0) HWTEST_F(BmsDataMgrTest, AddBundleInfo_0300, Function | SmallTest | Level0) { auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); InnerBundleInfo info; bool ret = dataMgr->AddInnerBundleInfo("", info); EXPECT_FALSE(ret); @@ -634,7 +634,7 @@ HWTEST_F(BmsDataMgrTest, AddBundleInfo_0400, Function | SmallTest | Level0) info.SetBaseBundleInfo(bundleInfo); info.SetBaseApplicationInfo(applicationInfo); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->AddInnerBundleInfo(BUNDLE_NAME, info); @@ -687,7 +687,7 @@ HWTEST_F(BmsDataMgrTest, AddBundleInfo_0500, Function | SmallTest | Level0) InnerBundleInfo info3; InnerBundleInfo info4; auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->AddInnerBundleInfo(BUNDLE_NAME, info1); @@ -734,7 +734,7 @@ HWTEST_F(BmsDataMgrTest, GenerateUidAndGid_0100, Function | SmallTest | Level0) info.SetBaseApplicationInfo(applicationInfo); info.SetAppType(Constants::AppType::SYSTEM_APP); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->AddInnerBundleInfo(BUNDLE_NAME, info); @@ -767,7 +767,7 @@ HWTEST_F(BmsDataMgrTest, GenerateUidAndGid_0200, Function | SmallTest | Level0) info.SetBaseApplicationInfo(applicationInfo); info.SetAppType(Constants::AppType::THIRD_SYSTEM_APP); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->AddInnerBundleInfo(BUNDLE_NAME, info); @@ -800,7 +800,7 @@ HWTEST_F(BmsDataMgrTest, GenerateUidAndGid_0300, Function | SmallTest | Level0) info.SetBaseApplicationInfo(applicationInfo); info.SetAppType(Constants::AppType::THIRD_PARTY_APP); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->AddInnerBundleInfo(BUNDLE_NAME, info); @@ -836,7 +836,7 @@ HWTEST_F(BmsDataMgrTest, QueryAbilityInfo_0100, Function | SmallTest | Level0) info1.SetBaseApplicationInfo(applicationInfo1); info1.InsertAbilitiesInfo(BUNDLE_NAME + PACKAGE_NAME + ABILITY_NAME, abilityInfo); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); EXPECT_TRUE(ret1); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); @@ -893,7 +893,7 @@ HWTEST_F(BmsDataMgrTest, QueryAbilityInfo_0200, Function | SmallTest | Level0) name.SetAbilityName(ABILITY_NAME); want.SetElement(name); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); AbilityInfo abilityInfo; bool ret = dataMgr->QueryAbilityInfo(want, abilityInfo); EXPECT_FALSE(ret); @@ -937,7 +937,7 @@ HWTEST_F(BmsDataMgrTest, QueryAbilityInfo_0300, Function | SmallTest | Level0) want.SetElement(element1); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); AbilityInfo abilityInfo; bool ret = dataMgr->QueryAbilityInfo(want, abilityInfo); EXPECT_FALSE(ret); @@ -961,7 +961,7 @@ HWTEST_F(BmsDataMgrTest, GetApplicationInfo_0100, Function | SmallTest | Level0) info1.SetBaseBundleInfo(bundleInfo1); info1.SetBaseApplicationInfo(applicationInfo1); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool ret1 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_START); bool ret2 = dataMgr->UpdateBundleInstallState(BUNDLE_NAME, InstallState::INSTALL_SUCCESS); bool ret3 = dataMgr->AddInnerBundleInfo(BUNDLE_NAME, info1); @@ -999,7 +999,7 @@ HWTEST_F(BmsDataMgrTest, GetApplicationInfo_0200, Function | SmallTest | Level0) EXPECT_EQ(appInfo.bundleName, appInfo2->bundleName); EXPECT_EQ(appInfo.deviceId, appInfo2->deviceId); auto dataMgr = GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); ApplicationInfo appInfo3; bool ret = dataMgr->GetApplicationInfo(BUNDLE_NAME, ApplicationFlag::GET_BASIC_APPLICATION_INFO, USERID, appInfo3); EXPECT_FALSE(ret); diff --git a/services/bundlemgr/test/unittest/bms_install_daemon_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_install_daemon_test/BUILD.gn old mode 100644 new mode 100755 index f36436d0322ea810069ec712a143bd19c9b500be..977f83f9bc4553c986f76cd9e75dc88c67cc78cd --- a/services/bundlemgr/test/unittest/bms_install_daemon_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_install_daemon_test/BUILD.gn @@ -20,7 +20,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsInstallDaemonTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${services_path}/bundlemgr/src/installd_death_recipient.cpp", "${services_path}/bundlemgr/test/mock/src/system_ability_helper.cpp", @@ -41,6 +41,7 @@ ohos_unittest("BmsInstallDaemonTest") { "${services_path}/bundlemgr:bundle_parser", "${services_path}/bundlemgr:parser_common", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ diff --git a/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp b/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp index f644149bcd401ed7a05823f1a331bd5821b93de9..b8c87eb818c94cad76075914e36c464a78b5dd80 100755 --- a/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp +++ b/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp @@ -74,13 +74,13 @@ void BmsInstallDaemonTest::SetUpTestCase() { if (access(ROOT_DIR.c_str(), F_OK) != 0) { bool result = OHOS::ForceCreateDirectory(ROOT_DIR); - ASSERT_TRUE(result) << "fail to create root dir"; + EXPECT_TRUE(result) << "fail to create root dir"; } if (chown(ROOT_DIR.c_str(), ROOT_UID, ROOT_UID) != 0) { - ASSERT_TRUE(false) << "fail to change root dir own ship"; + EXPECT_TRUE(false) << "fail to change root dir own ship"; } if (chmod(ROOT_DIR.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { - ASSERT_TRUE(false) << "fail to change root dir mode"; + EXPECT_TRUE(false) << "fail to change root dir mode"; } } @@ -186,9 +186,9 @@ bool BmsInstallDaemonTest::CheckBundleDataDirExist() const HWTEST_F(BmsInstallDaemonTest, Startup_0100, Function | SmallTest | Level0) { std::shared_ptr installdService = std::make_shared(); - ASSERT_NE(installdService, nullptr); + EXPECT_NE(installdService, nullptr); bool ready = installdService->IsServiceReady(); - ASSERT_EQ(false, ready); + EXPECT_EQ(false, ready); installdService->Start(); ready = installdService->IsServiceReady(); EXPECT_EQ(true, ready); @@ -203,10 +203,10 @@ HWTEST_F(BmsInstallDaemonTest, Startup_0100, Function | SmallTest | Level0) HWTEST_F(BmsInstallDaemonTest, Startup_0200, Function | SmallTest | Level0) { std::shared_ptr installdService = std::make_shared(); - ASSERT_NE(installdService, nullptr); + EXPECT_NE(installdService, nullptr); installdService->Start(); bool ready = installdService->IsServiceReady(); - ASSERT_EQ(true, ready); + EXPECT_EQ(true, ready); installdService->Stop(); ready = installdService->IsServiceReady(); EXPECT_EQ(false, ready); @@ -221,13 +221,13 @@ HWTEST_F(BmsInstallDaemonTest, Startup_0200, Function | SmallTest | Level0) HWTEST_F(BmsInstallDaemonTest, Startup_0300, Function | SmallTest | Level0) { std::shared_ptr installdService = std::make_shared(); - ASSERT_NE(installdService, nullptr); + EXPECT_NE(installdService, nullptr); installdService->Start(); bool ready = installdService->IsServiceReady(); - ASSERT_EQ(true, ready); + EXPECT_EQ(true, ready); installdService->Stop(); ready = installdService->IsServiceReady(); - ASSERT_EQ(false, ready); + EXPECT_EQ(false, ready); installdService->Start(); ready = installdService->IsServiceReady(); EXPECT_EQ(true, ready); @@ -242,10 +242,10 @@ HWTEST_F(BmsInstallDaemonTest, Startup_0300, Function | SmallTest | Level0) HWTEST_F(BmsInstallDaemonTest, Startup_0400, Function | SmallTest | Level0) { std::shared_ptr installdService = std::make_shared(); - ASSERT_NE(installdService, nullptr); + EXPECT_NE(installdService, nullptr); installdService->Start(); bool ready = installdService->IsServiceReady(); - ASSERT_EQ(true, ready); + EXPECT_EQ(true, ready); installdService->Start(); ready = installdService->IsServiceReady(); EXPECT_EQ(true, ready); @@ -272,9 +272,9 @@ HWTEST_F(BmsInstallDaemonTest, Communication_0100, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, Communication_0200, Function | SmallTest | Level0) { std::shared_ptr installdService = std::make_shared(); - ASSERT_NE(installdService, nullptr); + EXPECT_NE(installdService, nullptr); bool ready = installdService->IsServiceReady(); - ASSERT_EQ(false, ready); + EXPECT_EQ(false, ready); InstalldClient::GetInstance()->ResetInstalldProxy(); int result = InstalldClient::GetInstance()->CreateBundleDir(BUNDLE_CODE_DIR); EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); @@ -301,9 +301,9 @@ HWTEST_F(BmsInstallDaemonTest, Communication_0300, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, Communication_0400, Function | SmallTest | Level0) { std::shared_ptr installdService = std::make_shared(); - ASSERT_NE(installdService, nullptr); + EXPECT_NE(installdService, nullptr); bool ready = installdService->IsServiceReady(); - ASSERT_EQ(false, ready); + EXPECT_EQ(false, ready); InstalldClient::GetInstance()->ResetInstalldProxy(); int result = InstalldClient::GetInstance()->CreateBundleDataDir(BUNDLE_DATA_DIR, UID, GID); EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_GET_PROXY_ERROR); @@ -318,11 +318,11 @@ HWTEST_F(BmsInstallDaemonTest, Communication_0400, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, BundleDir_0100, Function | SmallTest | Level0) { int result = CreateBundleDir(BUNDLE_CODE_DIR); - ASSERT_EQ(result, 0); + EXPECT_EQ(result, 0); bool dirExist = CheckBundleDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); int result1 = RemoveBundleDir(BUNDLE_CODE_DIR); - ASSERT_EQ(result1, 0); + EXPECT_EQ(result1, 0); dirExist = CheckBundleDirExist(); EXPECT_FALSE(dirExist); } @@ -336,7 +336,7 @@ HWTEST_F(BmsInstallDaemonTest, BundleDir_0100, Function | SmallTest | Level0) HWTEST_F(BmsInstallDaemonTest, BundleDir_0200, Function | SmallTest | Level0) { int result = CreateBundleDir(""); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); bool dirExist = CheckBundleDirExist(); EXPECT_FALSE(dirExist); } @@ -350,7 +350,7 @@ HWTEST_F(BmsInstallDaemonTest, BundleDir_0200, Function | SmallTest | Level0) HWTEST_F(BmsInstallDaemonTest, BundleDir_0300, Function | SmallTest | Level0) { int result1 = CreateBundleDir(SYSTEM_DIR); - ASSERT_EQ(result1, ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED); + EXPECT_EQ(result1, ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED); bool dirExist = CheckBundleDirExist(); EXPECT_FALSE(dirExist); } @@ -364,11 +364,11 @@ HWTEST_F(BmsInstallDaemonTest, BundleDir_0300, Function | SmallTest | Level0) HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0100, Function | SmallTest | Level0) { int result = CreateBundleDataDir(BUNDLE_DATA_DIR, UID, GID); - ASSERT_EQ(result, 0); + EXPECT_EQ(result, 0); bool dirExist = CheckBundleDataDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); int result1 = RemoveBundleDataDir(BUNDLE_DATA_DIR); - ASSERT_EQ(result1, 0); + EXPECT_EQ(result1, 0); dirExist = CheckBundleDataDirExist(); EXPECT_FALSE(dirExist); } @@ -382,11 +382,11 @@ HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0100, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0200, Function | SmallTest | Level0) { int result = CreateBundleDataDir(BUNDLE_DATA_DIR, UID, GID); - ASSERT_EQ(result, 0); + EXPECT_EQ(result, 0); bool dirExist = CheckBundleDataDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); int result1 = CleanBundleDataDir(BUNDLE_DATA_DIR); - ASSERT_EQ(result1, 0); + EXPECT_EQ(result1, 0); dirExist = CheckBundleDataDirExist(); EXPECT_TRUE(dirExist); } @@ -400,7 +400,7 @@ HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0200, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0300, Function | SmallTest | Level0) { int result = CreateBundleDataDir("", UID, GID); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); bool dirExist = CheckBundleDataDirExist(); EXPECT_FALSE(dirExist); } @@ -414,7 +414,7 @@ HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0300, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0400, Function | SmallTest | Level0) { int result = CreateBundleDataDir(BUNDLE_DATA_DIR, -1, GID); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); bool dirExist = CheckBundleDataDirExist(); EXPECT_FALSE(dirExist); } @@ -428,7 +428,7 @@ HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0400, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0500, Function | SmallTest | Level0) { int result = CreateBundleDataDir(BUNDLE_DATA_DIR, UID, -1); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); bool dirExist = CheckBundleDataDirExist(); EXPECT_FALSE(dirExist); } @@ -442,7 +442,7 @@ HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0500, Function | SmallTest | Level0 HWTEST_F(BmsInstallDaemonTest, BundleDataDir_0600, Function | SmallTest | Level0) { int result = CreateBundleDataDir(SYSTEM_DIR, UID, GID); - ASSERT_EQ(result, ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED); + EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED); bool dirExist = CheckBundleDataDirExist(); EXPECT_FALSE(dirExist); } @@ -457,10 +457,10 @@ HWTEST_F(BmsInstallDaemonTest, ExtractBundleFile_0100, Function | SmallTest | Le { CreateBundleDir(BUNDLE_CODE_DIR); bool dirExist = CheckBundleDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); auto bundleFile = BUNDLE_FILE; int result = ExtractModuleFiles(bundleFile, TEMP_DIR); - ASSERT_EQ(result, 0); + EXPECT_EQ(result, 0); int result1 = RenameModuleDir(TEMP_DIR, MODULE_DIR); EXPECT_EQ(result1, 0); } @@ -475,7 +475,7 @@ HWTEST_F(BmsInstallDaemonTest, ExtractBundleFile_0200, Function | SmallTest | Le { CreateBundleDir(BUNDLE_CODE_DIR); bool dirExist = CheckBundleDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); int result = ExtractModuleFiles("", TEMP_DIR); EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); } @@ -490,7 +490,7 @@ HWTEST_F(BmsInstallDaemonTest, ExtractBundleFile_0300, Function | SmallTest | Le { CreateBundleDir(BUNDLE_CODE_DIR); bool dirExist = CheckBundleDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); auto bundleFile = BUNDLE_FILE; int result = ExtractModuleFiles(bundleFile, ""); EXPECT_EQ(result, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); @@ -506,10 +506,10 @@ HWTEST_F(BmsInstallDaemonTest, ExtractBundleFile_0400, Function | SmallTest | Le { CreateBundleDir(BUNDLE_CODE_DIR); bool dirExist = CheckBundleDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); auto bundleFile = BUNDLE_FILE; int result = ExtractModuleFiles(bundleFile, TEMP_DIR); - ASSERT_EQ(result, 0); + EXPECT_EQ(result, 0); int result1 = RenameModuleDir("", MODULE_DIR); EXPECT_EQ(result1, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); } @@ -524,10 +524,10 @@ HWTEST_F(BmsInstallDaemonTest, ExtractBundleFile_0500, Function | SmallTest | Le { CreateBundleDir(BUNDLE_CODE_DIR); bool dirExist = CheckBundleDirExist(); - ASSERT_TRUE(dirExist); + EXPECT_TRUE(dirExist); auto bundleFile = BUNDLE_FILE; int result = ExtractModuleFiles(bundleFile, TEMP_DIR); - ASSERT_EQ(result, 0); + EXPECT_EQ(result, 0); int result1 = RenameModuleDir(TEMP_DIR, ""); EXPECT_EQ(result1, ERR_APPEXECFWK_INSTALLD_PARAM_ERROR); } diff --git a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/BUILD.gn old mode 100644 new mode 100755 index df19802567218138d3676c6c90ca49c2884777cd..77e8ff494b89a34ee8e363f46c6cf8bd6ca7f852 --- a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/BUILD.gn @@ -20,7 +20,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsServiceBundleScanTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${services_path}/bundlemgr/src/bundle_data_mgr.cpp", "${services_path}/bundlemgr/src/bundle_data_storage_database.cpp", @@ -29,6 +29,9 @@ ohos_unittest("BmsServiceBundleScanTest") { "${services_path}/bundlemgr/src/bundle_mgr_service_event_handler.cpp", "${services_path}/bundlemgr/src/bundle_scanner.cpp", "${services_path}/bundlemgr/src/bundle_status_callback_death_recipient.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += @@ -56,6 +59,7 @@ ohos_unittest("BmsServiceBundleScanTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] deps += bundle_install_deps diff --git a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp index 8abd6d4c9ee504e58be5e71f6b5f71ee210c5de6..b7fbba7d28ce534b5282194dfd1949a21a122ed8 100755 --- a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp +++ b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp @@ -110,27 +110,17 @@ void BmsServiceBundleScanTest::CreateFile(const std::string &path) const APP_LOGE("path too long"); return; } - std::string realPath; - realPath.reserve(PATH_MAX); - realPath.resize(PATH_MAX - 1); - - // if path not exist, realpath return nullptr && result put into buffer of second pointer - if (realpath(path.c_str(), &(realPath[0])) == nullptr) { - APP_LOGW("CreateFile-translate:%{public}s not exist path", realPath.c_str()); - } - mode_t mode = 0666; - int fd = open(realPath.c_str(), O_RDWR | O_CREAT, mode); + int fd = open(path.c_str(), O_RDWR | O_CREAT, mode); if (fd == -1) { - APP_LOGE("CreateFile-open:%{public}s error", realPath.c_str()); + APP_LOGE("CreateFile-open:%{public}s error", path.c_str()); return; } if (close(fd) != 0) { - APP_LOGW("CreateFile-close:%{public}s error", realPath.c_str()); + APP_LOGW("CreateFile-close:%{public}s error", path.c_str()); } - - if (access(realPath.c_str(), F_OK) != 0) { - APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); + if (access(path.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", path.c_str()); } } @@ -198,7 +188,7 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0300, Function | SmallTest | Level CreateFile(TEST_FILE_NAME_3); int number = static_cast(TriggerScan()); - ASSERT_EQ(3, number); + EXPECT_EQ(3, number); EXPECT_TRUE(IsScanResultContain(TEST_FILE_NAME_1)); EXPECT_TRUE(IsScanResultContain(TEST_FILE_NAME_2)); @@ -254,7 +244,7 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0500, Function | SmallTest | Level CreateFile(TEST_FILE_NAME_6); int number = static_cast(TriggerScan()); - ASSERT_EQ(3, number); + EXPECT_EQ(3, number); EXPECT_TRUE(IsScanResultContain(TEST_FILE_NAME_1)); EXPECT_TRUE(IsScanResultContain(TEST_FILE_NAME_2)); diff --git a/services/bundlemgr/test/unittest/bms_service_startup_test/BUILD.gn b/services/bundlemgr/test/unittest/bms_service_startup_test/BUILD.gn old mode 100644 new mode 100755 index f6486bdf038d0a323410b5aa5e834e45e043785b..9ac08d9de4efd256189941f8f31fb6794fe5fdba --- a/services/bundlemgr/test/unittest/bms_service_startup_test/BUILD.gn +++ b/services/bundlemgr/test/unittest/bms_service_startup_test/BUILD.gn @@ -20,7 +20,7 @@ module_output_path = "appexecfwk_standard/bundlemgrservice" ohos_unittest("BmsServiceStartupTest") { module_out_path = module_output_path - + include_dirs = [ "//third_party/jsoncpp/include" ] sources = [ "${services_path}/bundlemgr/src/bundle_data_mgr.cpp", "${services_path}/bundlemgr/src/bundle_data_storage_database.cpp", @@ -29,6 +29,9 @@ ohos_unittest("BmsServiceStartupTest") { "${services_path}/bundlemgr/src/bundle_mgr_service_event_handler.cpp", "${services_path}/bundlemgr/src/bundle_scanner.cpp", "${services_path}/bundlemgr/src/bundle_status_callback_death_recipient.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += @@ -56,6 +59,7 @@ ohos_unittest("BmsServiceStartupTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp b/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp index 82311aceb248b6adf44a8ab8c361d7076fd53304..5605132d410dc0c6433568a766684140db264aa3 100755 --- a/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp +++ b/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp @@ -55,7 +55,7 @@ HWTEST_F(BmsServiceStartupTest, Startup_0100, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bool ready = bms->IsServiceReady(); - ASSERT_EQ(false, ready); + EXPECT_EQ(false, ready); bms->OnStart(); ready = bms->IsServiceReady(); EXPECT_EQ(true, ready); @@ -72,7 +72,7 @@ HWTEST_F(BmsServiceStartupTest, Startup_0200,Function | SmallTest | Level0) std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); bool ready = bms->IsServiceReady(); - ASSERT_EQ(true, ready); + EXPECT_EQ(true, ready); bms->OnStop(); ready = bms->IsServiceReady(); EXPECT_EQ(false, ready); @@ -89,10 +89,10 @@ HWTEST_F(BmsServiceStartupTest, Startup_0300,Function | SmallTest | Level0) std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); bool ready = bms->IsServiceReady(); - ASSERT_EQ(true, ready); + EXPECT_EQ(true, ready); bms->OnStop(); ready = bms->IsServiceReady(); - ASSERT_EQ(false, ready); + EXPECT_EQ(false, ready); bms->OnStart(); ready = bms->IsServiceReady(); EXPECT_EQ(true, ready); @@ -109,7 +109,7 @@ HWTEST_F(BmsServiceStartupTest, Startup_0400,Function | SmallTest | Level0) std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); bool ready = bms->IsServiceReady(); - ASSERT_EQ(true, ready); + EXPECT_EQ(true, ready); bms->OnStart(); ready = bms->IsServiceReady(); EXPECT_EQ(true, ready); diff --git a/services/formmgr/BUILD.gn b/services/formmgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9036ae87b33c76b545e193eaaee5fa0418013de1 --- /dev/null +++ b/services/formmgr/BUILD.gn @@ -0,0 +1,111 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +config("formmgr_config") { + include_dirs = [ + "include", + "//third_party/json/include", + "//utils/system/safwk/native/include", + ] + cflags_cc = [ "-fexceptions" ] +} + +group("fms_target") { + deps = [ ":libfms" ] +} + +ohos_shared_library("libfms") { + include_dirs = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", + + # "//third_party/libuuid", + ] + sources = [ + "src/form_ability_connection.cpp", + "src/form_acquire_connection.cpp", + "src/form_ams_helper.cpp", + "src/form_batch_delete_connection.cpp", + "src/form_bms_helper.cpp", + "src/form_cache_mgr.cpp", + "src/form_cast_temp_connection.cpp", + "src/form_data_mgr.cpp", + "src/form_db_cache.cpp", + "src/form_db_info.cpp", + "src/form_delete_connection.cpp", + "src/form_dump_mgr.cpp", + "src/form_event_notify_connection.cpp", + "src/form_host_callback.cpp", + "src/form_host_record.cpp", + "src/form_item_info.cpp", + "src/form_mgr_adapter.cpp", + "src/form_mgr_service.cpp", + "src/form_msg_event_connection.cpp", + "src/form_provider_mgr.cpp", + "src/form_refresh_connection.cpp", + "src/form_refresh_limiter.cpp", + "src/form_storage_mgr.cpp", + "src/form_supply_callback.cpp", + "src/form_sys_event_receiver.cpp", + "src/form_task_mgr.cpp", + "src/form_timer_mgr.cpp", + "src/form_util.cpp", + ] + + defines = [ + "APP_LOG_TAG = \"FormMgrService\"", + "LOG_DOMAIN = 0xD001120", + ] + + configs = [ + ":formmgr_config", + "//base/miscservices/time/services:time_service_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${libs_path}/libeventhandler:libeventhandler_target", + "//base/powermgr/power_manager/interfaces/innerkits:powermgr_client", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + + # "//third_party/libuuid:libuuid_static", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "os_account_standard:libaccountkits", + ] + + subsystem_name = "appexecfwk" + part_name = "appexecfwk_standard" +} diff --git a/services/formmgr/include/form_ability_connection.h b/services/formmgr/include/form_ability_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..8794c9ffa754e2a9b38d7c838e106fed6a531a71 --- /dev/null +++ b/services/formmgr/include/form_ability_connection.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H + +#include "event_handler.h" +#include "form_item_info.h" +#include "provider_connect_stub.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormAbilityConnection + * Form Ability Connection Stub. + */ +class FormAbilityConnection : public ProviderConnectStub { +public: + FormAbilityConnection() = default; + virtual ~FormAbilityConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + /** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + + /** + * @brief remote object died event. + * @param remoteObject the remote object of service ability. + */ + void OnConnectDied(const wptr &remoteObject); + + /** + * @brief Get connectId. + * @return The ability connection id. + */ + long GetConnectId(); + + /** + * @brief Set connectId. + * @param connectId The ability connection id. + */ + void SetConnectId(long connectId); + + // std::string GetProviderKey(); + +private: + int64_t formId_; + std::string deviceId_; + std::string bundleName_; + std::string abilityName_; + bool isFreeInstall_; + long connectId_ = 0; + + DISALLOW_COPY_AND_MOVE(FormAbilityConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_acquire_connection.h b/services/formmgr/include/form_acquire_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..8f680067d30c99f01fb0aa8245335f1c380cca70 --- /dev/null +++ b/services/formmgr/include/form_acquire_connection.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ACQUIRE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ACQUIRE_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "form_item_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormAcquireConnection + * Form Acquire Connection Stub. + */ +class FormAcquireConnection : public FormAbilityConnection { +public: + FormAcquireConnection(const int64_t formId, const FormItemInfo &info, const WantParams &wantParams); + virtual ~FormAcquireConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + FormItemInfo info_; + WantParams wantParams_; + + DISALLOW_COPY_AND_MOVE(FormAcquireConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ACQUIRE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_ams_helper.h b/services/formmgr/include/form_ams_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..1d554279be383ef37223b2c09dda5b37572b1003 --- /dev/null +++ b/services/formmgr/include/form_ams_helper.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_AMS_HELPER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_AMS_HELPER_H + +#include +#include +#include "ability_connect_callback_interface.h" +#include "ability_manager_interface.h" +#include "iremote_object.h" +#include "uri.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; +using IAbilityManager = OHOS::AAFwk::IAbilityManager; +using Want = OHOS::AAFwk::Want; +/** + * @class FormAmsHelper + * Ams helpler. + */ +class FormAmsHelper final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormAmsHelper) +public: + DISALLOW_COPY_AND_MOVE(FormAmsHelper); + + /** + * @brief acquire a form ability manager if it not existed, + * @return returns the ability manager ipc object or nullptr for failed. + */ + sptr GetAbilityManager(); + /** + * @brief Connect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ConnectServiceAbility( + const Want &want, const sptr &connect); + /** + * @brief Disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DisConnectServiceAbility(const sptr &connect); + /** + * @brief Add the ability manager instance for debug. + * @param abilityManager the ability manager ipc object. + */ + void SetAbilityManager(const sptr &abilityManager); +private: + sptr abilityManager_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_AMS_HELPER_H diff --git a/services/formmgr/include/form_batch_delete_connection.h b/services/formmgr/include/form_batch_delete_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..93dcf7cda997dad7912c3c5db239a265dd16e568 --- /dev/null +++ b/services/formmgr/include/form_batch_delete_connection.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BATCH_DELETE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BATCH_DELETE_CONNECTION_H + +#include + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormBatchDeleteConnection + * Form batch delete connection stub. + */ +class FormBatchDeleteConnection : public FormAbilityConnection { +public: + FormBatchDeleteConnection(const std::set &formIds); + virtual ~FormBatchDeleteConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + std::set formIds_; + + DISALLOW_COPY_AND_MOVE(FormBatchDeleteConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BATCH_DELETE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_bms_helper.h b/services/formmgr/include/form_bms_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..8d377a18261503489b0f98a534fabc9bfedaef8d --- /dev/null +++ b/services/formmgr/include/form_bms_helper.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BMS_HELPER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BMS_HELPER_H + +#include +#include "ability_connect_callback_interface.h" +#include "ability_manager_interface.h" +#include "bundle_info.h" +#include "bundle_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; +using IAbilityManager = OHOS::AAFwk::IAbilityManager; +using Want = OHOS::AAFwk::Want; + +/** + * @class FormBmsHelper + * Bms helpler. + */ +class FormBmsHelper final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormBmsHelper) + +public: + DISALLOW_COPY_AND_MOVE(FormBmsHelper); + + /** + * @brief Notify module removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ + void NotifyModuleRemovable(const std::string &bundleName, const std::string &moduleName); + /** + * @brief Notify module not removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ + void NotifyModuleNotRemovable(const std::string &bundleName, const std::string &moduleName) const; + + /** + * @brief Acquire a bundle manager, if it not existed, + * @return returns the bundle manager ipc object, or nullptr for failed. + */ + sptr GetBundleMgr(); + + /** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ + void SetBundleManager(const sptr &bundleManager); + +private: + /** + * @brief Generate module key. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + * @return Module key. + */ + std::string GenerateModuleKey(const std::string &bundleName, const std::string &moduleName) const; + +private: + sptr iBundleMgr_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_BMS_HELPER_H diff --git a/services/formmgr/include/form_cache_mgr.h b/services/formmgr/include/form_cache_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..d6fb1803dbeecd592d602d3eabc5315649df99c2 --- /dev/null +++ b/services/formmgr/include/form_cache_mgr.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CACHE_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CACHE_MGR_H + +#include +#include +#include +#include +#include + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormCacheMgr + * Form cache data manager. + */ +class FormCacheMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormCacheMgr) +public: + DISALLOW_COPY_AND_MOVE(FormCacheMgr); + + /** + * @brief Get form data. + * @param formId Form id. + * @param data Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetData(const int64_t formId, std::string &data) const; + + /** + * @brief Add form data. + * @param formId Form id. + * @param data Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool AddData(const int64_t formId, const std::string &data); + + /** + * @brief Delete form data. + * @param formId Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteData(const int64_t formId); + + /** + * @brief update form data. + * @param formId Form id. + * @param data Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UpdateData(const int64_t formId, const std::string &data); + /** + * @brief Check if form data is exist or not. + * @param formId, Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool IsExist(const int64_t formId) const; +private: + mutable std::mutex cacheMutex_; + std::map cacheData_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CACHE_MGR_H diff --git a/services/formmgr/include/form_cast_temp_connection.h b/services/formmgr/include/form_cast_temp_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..d0892a79548e09afa115202a2e5185aed65493d9 --- /dev/null +++ b/services/formmgr/include/form_cast_temp_connection.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormCastTempConnection + * Cast temp form Connection Stub. + */ +class FormCastTempConnection : public FormAbilityConnection { +public: + FormCastTempConnection(const int64_t formId); + virtual ~FormCastTempConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormCastTempConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_data_mgr.h b/services/formmgr/include/form_data_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..d4eb6d02cb72333e4e1afdd22a3686c2d74dcae3 --- /dev/null +++ b/services/formmgr/include/form_data_mgr.h @@ -0,0 +1,412 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DATA_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DATA_MGR_H + +#include +#include +#include +#include +#include +#include + +#include "form_host_record.h" +#include "form_id_key.h" +#include "form_info.h" +#include "form_item_info.h" +#include "form_js_info.h" +#include "form_record.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormDataMgr + * form data manager. + */ +class FormDataMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormDataMgr) +public: + DISALLOW_COPY_AND_MOVE(FormDataMgr); + /** + * @brief Allot form info by item info. + * @param formId The Id of the form. + * @param formInfo Form item info. + * @param callingUid The UID of the proxy. + * @return Returns form record. + */ + FormRecord AllotFormRecord(const FormItemInfo &formInfo, const int callingUid); + /** + * @brief Create form js info by form record. + * @param formId The Id of the form. + * @param record Form record. + * @param formInfo Js info. + * @return None. + */ + void CreateFormInfo(const int64_t formId, const FormRecord &record, FormJsInfo &formInfo); + /** + * @brief Delete form js info by form record. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteFormRecord(const int64_t formId); + /** + * @brief Clean removed forms for host. + * @param removedFormIds The id list of the forms. + */ + void CleanHostRemovedForms(const std::vector &removedFormIds); + /** + * @brief Delete form js info by form record. + * @return Returns all form records map. + */ + std::map &GetAllFormRecord(); + + /** + * @brief Get all form client host record. + * @return Returns all form client host record. + */ + std::vector &GetClientRecords(); + + /** + * @brief Get all form host records. + * @return Returns all form host records vector. + */ + std::vector &GetAllFormHostRecord(); + /** + * @brief Allot form host record by caller token. + * @param info The form item info. + * @param callerToken callerToken + * @param formId The Id of the form. + * @param callingUid The UID of the proxy. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool AllotFormHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int64_t formId, const int callingUid); + /** + * @brief Check temp form count is max. + * @return Returns ERR_OK if the temp form not reached; returns ERR_MAX_SYSTEM_TEMP_FORMS is reached. + */ + int CheckTempEnoughForm() const; + /** + * @brief Check form count is max. + * @param callingUid The UID of the proxy. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + int CheckEnoughForm(const int callingUid) const; + /** + * @brief Delete temp form. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteTempForm(const int64_t formId); + /** + * @brief Check temp form is exist. + * @param formId The Id of the form. + * @return Returns true if the temp form is exist; returns false is not exist. + */ + bool ExistTempForm(const int64_t formId) const; + /** + * @brief Modify form temp flag by formId. + * @param formId The Id of the form. + * @param formTempFlg The form temp flag. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool ModifyFormTempFlg(const int64_t formId, const bool formTempFlg); + /** + * @brief Add form user uid from form record. + * @param formId The Id of the form. + * @param formUserUid The form user uid. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool AddFormUserUid(const int64_t formId, const int32_t formUserUid); + /** + * @brief Delete form user uid from form record. + * @param formId The Id of the form. + * @param uid calling user id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteFormUserUid(const int64_t formId, const int32_t uid); + /** + * @brief Update form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool UpdateFormRecord(const int64_t formId, const FormRecord &formRecord); + /** + * @brief Get form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetFormRecord(const int64_t formId, FormRecord &formRecord) const; + /** + * @brief Get form record. + * @param bundleName Bundle name. + * @param formInfos The form record list. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetFormRecord(const std::string &bundleName, std::vector &formInfos); + /** + * @brief Check form record is exist. + * @param formId The Id of the form. + * @return Returns true if the form record is exist; returns false is not exist. + */ + bool ExistFormRecord(const int64_t formId) const; + /** + * @brief Has form user uids in form record. + * @param formId The Id of the form. + * @return Returns true if this form has form user uids; returns false is not has. + */ + bool HasFormUserUids(const int64_t formId) const; + /** + * @brief Get form host record. + * @param formId The id of the form. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GetFormHostRecord(const int64_t formId, FormHostRecord &formHostRecord) const; + /** + * @brief Delete form host record. + * @param callerToken The client stub of the form host record. + * @param formId The id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool DeleteHostRecord(const sptr &callerToken, const int64_t formId); + /** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ + void HandleHostDied(const sptr &remoteHost); + /** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable. + */ + bool IsEnableRefresh(int64_t formId); + /** + * @brief Check calling uid is valid. + * @param formUserUids The form user uids. + * @return Returns true if this user uid is valid; returns false otherwise. + */ + bool IsCallingUidValid(const std::vector &formUserUids) const; + /** + * @brief Generate udid. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool GenerateUdidHash(); + /** + * @brief Generate form id. + * @return form id. + */ + int64_t GenerateFormId(); + /** + * @brief Get udid. + * @return udid. + */ + int64_t GetUdidHash() const; + /** + * @brief Set udid. + * @param udidHash udid. + */ + void SetUdidHash(const int64_t udidHash); + + /** + * @brief Get the matched form host record by client stub. + * + * @param callerToken The client stub of the form host record. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called, returns false otherwise. + */ + bool GetMatchedHostClient(const sptr &callerToken, FormHostRecord &formHostRecord) const; + + /** + * @brief Set needRefresh for FormRecord. + * @param formId The Id of the form. + * @param needRefresh true or false. + */ + void SetNeedRefresh(const int64_t formId, const bool needRefresh); + /** + * @brief Set isCountTimerRefresh for FormRecord. + * @param formId The Id of the form. + * @param countTimerRefresh true or false. + */ + void SetCountTimerRefresh(const int64_t formId, const bool countTimerRefresh); + /** + * @brief Get updated form info. + * @param record FormRecord. + * @param targetForms Target forms. + * @param updatedForm Updated form info. + * @return Returns true on success, false on failure. + */ + bool GetUpdatedForm(const FormRecord &record, const std::vector &targetForms, FormInfo &updatedForm); + /** + * @brief Set isEnableUpdate for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + */ + void SetEnableUpdate(const int64_t formId, const bool enableUpdate); + /** + * @brief Set update info for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + * @param updateDuration Update duration. + * @param updateAtHour Update at hour. + * @param updateAtMin Update at minute. + */ + void SetUpdateInfo(const int64_t formId, const bool enableUpdate, const long updateDuration, + const int updateAtHour, const int updateAtMin); + /** + * @brief Clean removed form records. + * @param bundleName BundleName. + * @param removedForms The id list of the forms. + */ + void CleanRemovedFormRecords(const std::string &bundleName, std::set &removedForms); + /** + * @brief Clean removed temp form records. + * @param bundleName BundleName. + * @param removedForms The id list of the forms. + */ + void CleanRemovedTempFormRecords(const std::string &bundleName, std::set &removedForms); + /** + * @brief Get recreate form records. + * @param reCreateForms The id list of the forms. + */ + void GetReCreateFormRecordsByBundleName(const std::string &bundleName, std::set &reCreateForms); + /** + * @brief Set form isInited = true. + * @param formId The Id of the form. + * @param isInited isInited property + */ + void SetFormCacheInited(const int64_t formId, const bool isInited); + /** + * @brief Set versionUpgrade. + * @param formId The Id of the form. + * @param versionUpgrade true or false + */ + void SetVersionUpgrade(const int64_t formId, const bool versionUpgrade); + /** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param needRefresh true or false + */ + void UpdateHostNeedRefresh(const int64_t formId, const bool needRefresh); + /** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formRecord The form info. + * @return Returns true if form update, false if other. + */ + bool UpdateHostForm(const int64_t formId, const FormRecord &formRecord); + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @param refreshForms Refresh forms + * @return Returns ERR_OK on success, others on failure. + */ + int32_t UpdateHostFormFlag(std::vector formIds, const sptr &callerToken, + const bool flag, std::vector &refreshForms); + /** + * @brief Find matched form id. + * @param formId The form id. + * @return Matched form id. + */ + int64_t FindMatchedFormId(const int64_t formId); + /** + * @brief Clear host data by uId. + * @param uId The caller uId. + */ + void ClearHostDataByUId(const int uId); + /** + * @brief Get no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ + void GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, + std::map &foundFormsMap); +private: + /** + * @brief Create form record. + * @param formInfo The form item info. + * @param callingUid The UID of the proxy. + * @return Form record. + */ + FormRecord CreateFormRecord(const FormItemInfo &formInfo, const int callingUid) const; + /** + * @brief Create host record. + * @param info The form item info. + * @param callerToken The UID of the proxy. + * @param callingUid The UID of the proxy. + * @param record The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ + bool CreateHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int callingUid, FormHostRecord &record); + /** + * @brief Parse update config. + * @param record The form record. + * @param info The form item info. + * @return None. + */ + void ParseUpdateConfig(FormRecord &record, const FormItemInfo &info) const; + /** + * @brief Parse update interval config. + * @param record The form record. + * @param configDuration interval duration. + */ + void ParseIntervalConfig(FormRecord &record, const int configDuration) const; + /** + * @brief Parse at time config. + * @param record The form record. + * @param info form item info. + */ + void ParseAtTimerConfig(FormRecord record, const FormItemInfo &info) const; + /** + * @brief Get the temp forms from host and delete temp form in cache. + * @param record The form record. + * @param recordTempForms Getted the temp forms. + */ + void HandleHostDiedForTempForms(const FormHostRecord &record, std::vector &recordTempForms); + /** + * @brief Check if two forms is same or not. + * @param record FormRecord. + * @param formInfo FormInfo. + * @return Returns true on success, false on failure. + */ + bool IsSameForm(const FormRecord &record, const FormInfo &formInfo); + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ + bool IsFormCached(const FormRecord record); +private: + mutable std::mutex formRecordMutex_; + mutable std::mutex formHostRecordMutex_; + mutable std::mutex formTempMutex_; + std::map formRecords_; + std::vector clientRecords_; + std::vector tempForms_; + int64_t udidHash_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_DATA_MGR_H diff --git a/services/formmgr/include/form_db_cache.h b/services/formmgr/include/form_db_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..1be4e0fdd20955967e5fa78c2d968495ba37bf4c --- /dev/null +++ b/services/formmgr/include/form_db_cache.h @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DB_CACHE_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DB_CACHE_H + +#include +#include +#include + +#include "appexecfwk_errors.h" +#include "form_id_key.h" +#include "form_record.h" +#include "form_storage_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +class FormDbCache final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormDbCache) +public: + DISALLOW_COPY_AND_MOVE(FormDbCache); + + /** + * @brief Load form data from DB to DbCache when starting. + * @return Void. + */ + void Start(); + + /** + * @brief Get all form data from DbCache. + * @param formDBInfos Storage all DbCache. + * @return Void + */ + void GetAllFormInfo(std::vector &formDBInfos); + + /** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SaveFormInfo(const FormDBInfo &formDBInfo); + + /** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure.(NoLock) + */ + ErrCode SaveFormInfoNolock(const FormDBInfo &formDBInfo); + + /** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DeleteFormInfo(int64_t formId); + + /** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDBRecord(const int64_t formId, FormRecord &record) const; + /** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form db data + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetDBRecord(const int64_t formId, FormDBInfo &record) const; + /** + * @brief Use record save or update DB data and DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateDBRecord(const int64_t formId, const FormRecord &record) const; + + /** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @param removedDBForms Removed db form infos + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DeleteFormInfoByBundleName(const std::string &bundleName, std::vector &removedDBForms); + /** + * @brief Get no host db record. + * @param uid The caller uid. + * @param noHostFormDBList no host db record list. + * @param foundFormsMap Form Id list. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, + std::map &foundFormsMap); + /** + * @brief Get match count by bundleName and moduleName. + * @param bundleName BundleName. + * @param moduleName ModuleName. + * @return Returns match count. + */ + int GetMatchCount(const std::string &bundleName, const std::string &moduleName); +private: + std::unique_ptr dataStorage_; + mutable std::mutex formDBInfosMutex_; + std::vector formDBInfos_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DB_CACHE_H diff --git a/services/formmgr/include/form_db_info.h b/services/formmgr/include/form_db_info.h new file mode 100644 index 0000000000000000000000000000000000000000..8e18aaddc8857a50d199613dda6ba0a515fa51bb --- /dev/null +++ b/services/formmgr/include/form_db_info.h @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_INNER_FORM_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_INNER_FORM_INFO_H + +#include + +#include "form_record.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace AppExecFwk { +struct FormDBInfo { + int64_t formId; + std::string formName; + std::string bundleName; + std::string moduleName; + std::string abilityName; + std::vector formUserUids; + + /** + * @brief Constructors + * + */ + FormDBInfo() + { + formId = -1; + } + /** + * @brief Constructors + * + */ + FormDBInfo(const FormDBInfo &formDBInfo) + { + formId = formDBInfo.formId; + formName = formDBInfo.formName; + bundleName = formDBInfo.bundleName; + moduleName = formDBInfo.moduleName; + abilityName = formDBInfo.abilityName; + formUserUids = formDBInfo.formUserUids; + } + /** + * @brief Constructors + * + */ + FormDBInfo(const int64_t formIdTmp, const FormRecord &formRecord) + { + formId = formIdTmp; + formName = formRecord.formName; + bundleName = formRecord.bundleName; + moduleName = formRecord.moduleName; + abilityName = formRecord.abilityName; + formUserUids = formRecord.formUserUids; + } + bool Contains(const int uId) const + { + return std::find(formUserUids.begin(), formUserUids.end(), uId) != formUserUids.end(); + } + void Remove(const int uId) + { + auto itUId = std::find(formUserUids.begin(), formUserUids.end(), uId); + if (itUId != formUserUids.end()) { + formUserUids.erase(itUId); + } + } + /** + * @brief overloaded == for Indicates the formDBInfo by formId + * @return Returns true if the data equal; returns false otherwise. + */ + bool operator== (const FormDBInfo &formDBInfo) const + { + return (this->formId == formDBInfo.formId); + } + /** + * @brief Compare two data + * @return Returns true if the data equal; returns false otherwise. + */ + bool Compare(const FormDBInfo &formDBInfo) const + { + if (formId != formDBInfo.formId) { + return false; + } + if (formName != formDBInfo.formName) { + return false; + } + if (bundleName != formDBInfo.bundleName) { + return false; + } + if (moduleName != formDBInfo.moduleName) { + return false; + } + if (abilityName != formDBInfo.abilityName) { + return false; + } + if (formUserUids != formDBInfo.formUserUids) { + return false; + } + + return true; + } +}; + +class InnerFormInfo { +public: + /** + * @brief Constructors + */ + InnerFormInfo() + { + formDBInfo_.formId = -1; + } + /** + * @brief Constructors + * + */ + InnerFormInfo(const FormDBInfo &formDBInfo) + { + formDBInfo_.formId = formDBInfo.formId; + formDBInfo_.formName = formDBInfo.formName; + formDBInfo_.bundleName = formDBInfo.bundleName; + formDBInfo_.moduleName = formDBInfo.moduleName; + formDBInfo_.abilityName = formDBInfo.abilityName; + formDBInfo_.formUserUids = formDBInfo.formUserUids; + } + /** + * @brief Constructors + * + */ + InnerFormInfo(const InnerFormInfo &innerFormInfo) + { + formDBInfo_.formId = innerFormInfo.formDBInfo_.formId; + formDBInfo_.formName = innerFormInfo.formDBInfo_.formName; + formDBInfo_.bundleName = innerFormInfo.formDBInfo_.bundleName; + formDBInfo_.moduleName = innerFormInfo.formDBInfo_.moduleName; + formDBInfo_.abilityName = innerFormInfo.formDBInfo_.abilityName; + formDBInfo_.formUserUids = innerFormInfo.formDBInfo_.formUserUids; + } + /** + * @brief Constructors + * + */ + InnerFormInfo(const int64_t formId, const FormRecord &formRecord) + { + formDBInfo_.formId = formId; + formDBInfo_.formName = formRecord.formName; + formDBInfo_.bundleName = formRecord.bundleName; + formDBInfo_.moduleName = formRecord.moduleName; + formDBInfo_.abilityName = formRecord.abilityName; + formDBInfo_.formUserUids = formRecord.formUserUids; + } + /** + * @brief Destructor + * + */ + virtual ~InnerFormInfo(){}; + /** + * @brief overloaded == for Indicates the formInfo by formId + * @return Returns true if the data equal; returns false otherwise. + */ + bool operator== (const InnerFormInfo &innerFormInfo) const + { + return (this->formDBInfo_.formId == innerFormInfo.formDBInfo_.formId); + } + + /** + * @brief Transform the InnerFormInfo object to json. + * @param jsonObject Indicates the obtained json object. + */ + void ToJson(nlohmann::json &jsonObject) const; + + /** + * @brief Transform the json object to InnerFormInfo object. + * @param jsonObject Indicates the obtained json object. + * @return Returns true on success, false on failure. + */ + bool FromJson(const nlohmann::json &jsonObject); + + /** + * @brief Get application form id. + * @return Returns the form id. + */ + int64_t GetFormId() const + { + return formDBInfo_.formId; + } + + /** + * @brief Set application form id. + * @param formId Indicates the form id to be set. + */ + void SetFormId(const int64_t formId) + { + formDBInfo_.formId = formId; + } + + /** + * @brief Get application form name. + * @return Returns the form name. + */ + std::string GetModuleName() const + { + return formDBInfo_.moduleName; + } + + /** + * @brief Set application form name. + * @param formName Indicates the form name to be set. + */ + void SetModuleName(const std::string &moduleName) + { + formDBInfo_.moduleName = moduleName; + } + + /** + * @brief Get application bundle name. + * @return Returns the bundle name. + */ + std::string GetBundleName() const + { + return formDBInfo_.bundleName; + } + + /** + * @brief Set application bundle name. + * @param bundleName Indicates the bundle name to be set. + */ + void SetBundleName(const std::string &bundleName) + { + formDBInfo_.bundleName = bundleName; + } + + /** + * @brief Get application ability name. + * @return Returns the ability name. + */ + std::string GetAbilityName() const + { + return formDBInfo_.abilityName; + } + + /** + * @brief Set application ability name. + * @param abilityName Indicates the ability name to be set. + */ + void SetAbilityName(const std::string &abilityName) + { + formDBInfo_.abilityName = abilityName; + } + + /** + * @brief Get application formName. + * @return Returns the formName. + */ + std::string GetFormName() const + { + return formDBInfo_.formName; + } + + /** + * @brief Set application formName. + * @param userId Indicates the formName to be set. + */ + void SetFormName(std::string formName) + { + formDBInfo_.formName = formName; + } + + /** + * @brief Get application user uids. + * @return Returns the user uids. + */ + std::vector GetUserUids() const + { + return formDBInfo_.formUserUids; + } + + /** + * @brief Set application user uids. + * @param userId Indicates the user uids to be set. + */ + void SetUserUids(const std::vector &formUserUids) + { + formDBInfo_.formUserUids.insert(formDBInfo_.formUserUids.end(), formUserUids.begin(), formUserUids.end()); + } + + /** + * @brief Set application formRecord + * @param formRecord Indicates the formRecord to be set. + */ + void SetFormDBInfo(const FormDBInfo &formDBInfo) + { + formDBInfo_ = formDBInfo; + } + + /** + * @brief Get application formRecord. + * @return Returns the formRecord + */ + FormDBInfo GetFormDBInfo() const + { + return formDBInfo_; + } + + void AddUserUid(const int callingUid); + bool DeleteUserUid(const int callingUid); + +private: + FormDBInfo formDBInfo_; +}; + +// void to_json(nlohmann::json &jsonObject, const FormDBInfo &info); +// void from_json(const nlohmann::json &jsonObject, FormDBInfo &info); +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_INNER_FORM_INFO_H diff --git a/services/formmgr/include/form_delete_connection.h b/services/formmgr/include/form_delete_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..4da0e284061263ea6f9f370153e3ed5e5a01fd90 --- /dev/null +++ b/services/formmgr/include/form_delete_connection.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { + +/** + * @class FormDeleteConnection + * Form Delete Connection Stub. + */ +class FormDeleteConnection : public FormAbilityConnection { +public: + FormDeleteConnection(const int64_t formId); + virtual ~FormDeleteConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormDeleteConnection); +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_dump_mgr.h b/services/formmgr/include/form_dump_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..0d35da6141b64747b43b3e37018d345ab55a9d72 --- /dev/null +++ b/services/formmgr/include/form_dump_mgr.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DUMP_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DUMP_MGR_H + +#include + +#include "form_db_info.h" +#include "form_host_record.h" +#include "form_dump_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormDumpMgr + * Form dump mgr. + */ +class FormDumpMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormDumpMgr) +public: + DISALLOW_COPY_AND_MOVE(FormDumpMgr); + + /** + * @brief Dump all of form storage infos. + * @param storageInfos Form storage infos + * @param formInfos Form storage dump info. + */ + void DumpStorageFormInfos(const std::vector &storageInfos, std::string &formInfos) const; + /** + * @brief Dump form infos. + * @param formRecordInfos Form record infos. + * @param formInfos Form dump infos. + */ + void DumpFormInfos(const std::vector &formRecordInfos, std::string &formInfos) const; + /** + * @brief Dump form infos. + * @param formRecordInfo Form Host record info. + * @param formInfo Form dump info. + */ + void DumpFormHostInfo(const FormHostRecord &formHostRecord, std::string &formInfo) const; + /** + * @brief Dump form infos. + * @param formRecordInfo Form record info. + * @param formInfo Form dump info. + */ + void DumpFormInfo(const FormRecord &formRecordInfo, std::string &formInfo) const; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DUMP_MGR_H diff --git a/services/formmgr/include/form_event_notify_connection.h b/services/formmgr/include/form_event_notify_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..f06043a118fb0d6e97daffa69791431037b09ba4 --- /dev/null +++ b/services/formmgr/include/form_event_notify_connection.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormEventNotifyConnection + * Form Event Notify Connection Stub. + */ +class FormEventNotifyConnection : public FormAbilityConnection { +public: + FormEventNotifyConnection(const std::vector formEvents, const int32_t formVisibleType); + virtual ~FormEventNotifyConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + std::vector formEvents_; + int32_t formVisibleType_; + DISALLOW_COPY_AND_MOVE(FormEventNotifyConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_host_callback.h b/services/formmgr/include/form_host_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..fafe033c0058126c61a7d653096fa8c38740fa20 --- /dev/null +++ b/services/formmgr/include/form_host_callback.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_HOST_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_HOST_CALLBACK_H + +#include + +#include "form_js_info.h" +#include "form_record.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostCallback + * FormHost callback is used to call form host service. + */ +class FormHostCallback { +public: + FormHostCallback() = default; + virtual ~FormHostCallback() = default; + /** + * @brief Request to give back a Form. + * @param formId The Id of the forms to create. + * @param record Form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + void OnAcquired(const int64_t formId, const FormRecord &record, const sptr &callerToken); + + /** + * @brief Form is updated. + * @param formId The Id of the form to update. + * @param record Form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + void OnUpdate(const int64_t formId, const FormRecord &record, const sptr &callerToken); + + /** + * @brief Form provider is uninstalled. + * @param formIds The Id list of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + void OnUninstall(std::vector &formIds, const sptr &callerToken); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_HOST_CALLBACK_H diff --git a/services/formmgr/include/form_host_record.h b/services/formmgr/include/form_host_record.h new file mode 100644 index 0000000000000000000000000000000000000000..79e0869f7ba97a426680d979d15f8a89b1fbd025 --- /dev/null +++ b/services/formmgr/include/form_host_record.h @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H + +#include +#include +#include +#include "app_log_wrapper.h" +#include "form_host_callback.h" +#include "form_item_info.h" +#include "form_record.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostRecord + * Form host data. + */ +class FormHostRecord { +public: + /** + * @brief Create form host record. + * @param callback remote object. + * @param callingUid Calling uid. + */ + static FormHostRecord CreateRecord(const FormItemInfo &info, const sptr &callback, int callingUid); + /** + * @brief Add form id. + * @param formId The Id of the form. + */ + void AddForm(int64_t formId); + /** + * @brief Delete form id. + * @param formId The Id of the form. + */ + void DelForm(int64_t formId); + /** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ + bool IsEmpty() const; + /** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ + bool Contains(int64_t formId) const; + + /** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetEnableRefresh(int64_t formId, bool flag); + + /** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsEnableRefresh(int64_t formId) const; + + /** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetNeedRefresh(int64_t formId, bool flag); + /** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsNeedRefresh(int64_t formId) const; + + /** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnAcquire(int64_t id, const FormRecord &record); + + /** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnUpdate(int64_t id, const FormRecord &record); + /** + * Send form uninstall message to form host. + * + * @param id The Id of the form. + * @param record Form record. + */ + void OnFormUninstalled(std::vector &formIds); + + /** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ + void CleanResource(); + /** + * @brief Get callerUid_. + * @return callerUid_. + */ + int GetCallerUid() const + { + return callerUid_; + } + /** + * @brief Get clientStub_. + * @return clientStub_. + */ + sptr GetClientStub() const; + /** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ + sptr GetDeathRecipient() const; + /** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ + void SetCallerUid(const int callerUid); + /** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ + void SetClientStub(const sptr &clientStub); + /** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ + void SetClientImpl(const std::shared_ptr &clientImpl); + /** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ + void SetDeathRecipient(const sptr &deathRecipient); + /** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ + void AddDeathRecipient(const sptr& deathRecipient); + /** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ + std::string GetHostBundleName() const; + /** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ + void SetHostBundleName(const std::string &hostBundleName); + +private: + int callerUid_; + sptr clientStub_ = nullptr; + std::shared_ptr clientImpl_ = nullptr; + sptr deathRecipient_ = nullptr; + std::unordered_map forms_; + std::unordered_map needRefresh_; + std::string hostBundleName_; + + /** + * @class ClientDeathRecipient + * notices IRemoteBroker died. + */ + class ClientDeathRecipient : public IRemoteObject::DeathRecipient { + public: + /** + * @brief Constructor + */ + ClientDeathRecipient() = default; + ~ClientDeathRecipient() = default; + /** + * @brief handle remote object died event. + * @param remote remote object. + */ + void OnRemoteDied(const wptr &remote) override; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H \ No newline at end of file diff --git a/services/formmgr/include/form_id_key.h b/services/formmgr/include/form_id_key.h new file mode 100644 index 0000000000000000000000000000000000000000..53da57e89f19e5af8e4e03c0292c334dff6d6cd4 --- /dev/null +++ b/services/formmgr/include/form_id_key.h @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ID_KEY_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ID_KEY_H + +#include + +namespace OHOS { +namespace AppExecFwk { +struct FormIdKey { +public: + + std::string bundleName; + std::string moduleName; + std::string abilityName; + std::string formName; + int specificationId; + int orientation; + + bool operator== (const FormIdKey &formIdKey) const + { + return specificationId == formIdKey.specificationId + && orientation == formIdKey.orientation + && bundleName == formIdKey.bundleName + && moduleName == formIdKey.moduleName + && abilityName == formIdKey.abilityName + && formName == formIdKey.formName; + } + /** + * @brief overloaded == for Indicates the formDBInfo by formId + * @return Returns true if the data equal; returns false otherwise. + */ + bool operator< (const FormIdKey &formIdKey) const + { + return specificationId != formIdKey.specificationId + || orientation != formIdKey.orientation + || bundleName != formIdKey.bundleName + || moduleName != formIdKey.moduleName + || abilityName != formIdKey.abilityName + || formName != formIdKey.formName; + } + int hashCode() + { + return std::hash()(bundleName) + + std::hash()(moduleName) + + std::hash()(abilityName) + + std::hash()(formName) + + std::hash()(specificationId) + + std::hash()(orientation); + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ID_KEY_H diff --git a/services/formmgr/include/form_item_info.h b/services/formmgr/include/form_item_info.h new file mode 100644 index 0000000000000000000000000000000000000000..aa0a499ea0f80f6664da862396abb9a4a9e4738b --- /dev/null +++ b/services/formmgr/include/form_item_info.h @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CONFIG_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CONFIG_INFO_H + +#include +#include +#include +#include +#include "form_record.h" + +namespace OHOS { +namespace AppExecFwk { +class FormItemInfo { +public: + /** + * @brief Get formId_. + * @return formId_. + */ + int64_t GetFormId() const; + /** + * @brief Set value of formId_. + * @param formId Form Id. + */ + void SetFormId(int64_t formId); + /** + * @brief Get packageName_. + * @return packageName_. + */ + std::string GetPackageName() const; + /** + * @brief Set value of packageName_. + * @param packageName Package name. + */ + void SetPackageName(const std::string &packageName); + /** + * @brief Get providerBundleName_. + * @return providerBundleName_. + */ + std::string GetProviderBundleName() const; + /** + * @brief Set value of providerBundleName_. + * @param providerBundleName Provider bundle Name. + */ + void SetProviderBundleName(const std::string &providerBundleName_); + /** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ + std::string GetHostBundleName() const; + /** + * @brief Set value of hostBundleName_. + * @param hostBundleName_ Host bundle Name. + */ + void SetHostBundleName(const std::string &hostBundleName_); + /** + * @brief Get moduleName_. + * @return moduleName_. + */ + std::string GetModuleName() const; + /** + * @brief Set value of moduleName_. + * @param moduleName Module Name. + */ + void SetModuleName(const std::string &moduleName); + /** + * @brief Get abilityName_. + * @return abilityName_. + */ + std::string GetAbilityName() const; + /** + * @brief Set value of abilityName_. + * @param abilityName Ability name. + */ + void SetAbilityName(const std::string &abilityName); + /** + * @brief Get formName_. + * @return formName_. + */ + std::string GetFormName() const; + /** + * @brief Set value of formName_. + * @param formName Form name. + */ + void SetFormName(const std::string &formName); + /** + * @brief Get jsComponentName_. + * @return jsComponentName_. + */ + std::string GetJsComponentName() const; + /** + * @brief Set value of jsComponentName_. + * @param jsComponentName Js component name. + */ + void SetJsComponentName(const std::string &jsComponentName); + /** + * @brief Get abilityModuleName_. + * @return abilityModuleName_. + */ + std::string GetAbilityModuleName() const; + /** + * @brief Set value of abilityModuleName_. + * @param abilityModuleName ability module name_. + */ + void SetAbilityModuleName(const std::string &abilityModuleName); + /** + * @brief Get specificationId_. + * @return specificationId_. + */ + int GetSpecificationId() const; + /** + * @brief Set value of specificationId_. + * @param specificationId Specification id. + */ + void SetSpecificationId(const int specificationId); + + /** + * @brief Obtains the updageFlag. + * @return Returns updageFlag. + */ + bool IsEnableUpdateFlag() const; + /** + * @brief Set value of updateFlag_. + * @param IsEnableUpdateFlag Enable update flag or not. + */ + void SetEnableUpdateFlag(bool IsEnableUpdateFlag); + /** + * @brief Get updateDuration_. + * @return updateDuration_. + */ + int GetUpdateDuration() const; + /** + * @brief Set value of updateDuration_. + * @param updateDuration Update duration. + */ + void SetUpdateDuration(int updateDuration); + /** + * @brief Get scheduledUpdateTime_. + * @return scheduledUpdateTime_. + */ + std::string GetScheduledUpdateTime() const; + /** + * @brief Set value of scheduledUpdateTime_. + * @param scheduledUpdateTime Scheduled update time. + */ + void SetScheduledUpdateTime(const std::string &scheduledUpdateTime); + /** + * @brief Get hapSourceDirs_. + * @param dirs Hap source dirs. + * @return Returns true on success, false on failure. + */ + bool GetHapSourceDirs(std::vector &dirs) const; + /** + * @brief Add hap source dir. + * @param hapSourceDir Hap source dir. + */ + void AddHapSourceDirs(const std::string &hapSourceDir); + /** + * @brief Set value of hapSourceDirs_. + * @param hapSourceDirs Hap source dirs. + */ + void SetHapSourceDirs(const std::vector &hapSourceDirs); + /** + * @brief Obtains the temporaryFlag. + * @return Returns temporaryFlag. + */ + bool IsTemporaryForm() const; + /** + * @brief Set value of temporaryFlag_. + * @param temporaryFlag Temporary flag. + */ + void SetTemporaryFlag(bool temporaryFlag); + /** + * @brief Obtains the hap source by ability module name. + * @param moduleName ability module name + * @return Returns hap source. + */ + std::string GetHapSourceByModuleName(const std::string &moduleName) const; + /** + * @brief Add module info. + * @param moduleName Module name. + * @param moduleSourceDir Module source dir. + */ + void AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir); + /** + * @brief Check if item valid or not. + * @return Valid or not + */ + bool IsValidItem() const; + /** + * @brief Check if item match or not. + * @return Match or not + */ + bool IsMatch(const FormRecord &record) const; + /** + * @brief Check if form config same or not. + * @return Same or not + */ + bool IsSameFormConfig(const FormRecord &record) const; + /** + * @brief Check if visible notify or not. + * @return visible notify or not + */ + bool IsFormVisibleNotify() const; + /** + * @brief Set value of formVisibleNotify_. + * @param isFormVisibleNotify visible notify or not. + */ + void SetFormVisibleNotify(bool isFormVisibleNotify); +private: + /** + * @brief Equal or not. + * @param left left string. + * @param right right string. + * @return Equal or not + */ + bool IsEqual(const std::string &left, const std::string &right); + +private: + int64_t formId_ = -1; + std::string packageName_; + std::string providerBundleName_; + std::string hostBundleName_; + std::string moduleName_; + std::string abilityName_; + std::string formName_; + int32_t specificationId_; + bool updateFlag_; + int32_t updateDuration_; + std::string scheduledUpdateTime_; + std::vector hapSourceDirs_; + bool temporaryFlag_; + bool formVisibleNotify_; + + std::string jsComponentName_; + std::string abilityModuleName_; + std::unordered_map moduleInfoMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_CONFIG_INFO_H diff --git a/services/formmgr/include/form_mgr_adapter.h b/services/formmgr/include/form_mgr_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..b795fb900f38fe25f45a2090f04d2d7c9b0242a0 --- /dev/null +++ b/services/formmgr/include/form_mgr_adapter.h @@ -0,0 +1,383 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H + +#include + +#include "bundle_info.h" +#include "bundle_mgr_interface.h" +#include "form_info.h" +#include "form_host_record.h" +#include "form_item_info.h" +#include "form_js_info.h" +#include "form_provider_data.h" +#include "form_db_info.h" +#include "ipc_types.h" +#include "iremote_object.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +using WantParams = OHOS::AAFwk::WantParams; +/** + * @class FormMgrAdapter + * Form request handler from form host. + */ +class FormMgrAdapter { +public: + FormMgrAdapter(){}; + virtual ~FormMgrAdapter(){}; + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, FormJsInfo &formInfo); + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DeleteForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Release forms with formIds, send formIds to form Mgr service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache); + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formProviderData form provider data. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const std::string &bundleName, const FormProviderData &formProviderData); + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ + int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want); + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * + * @param formIds The vector of form Ids. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType); + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int CastTempForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpStorageFormInfos(std::string &formInfos) const; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) const; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const; + + /** + * @brief set next refresh time. + * @param formId The id of the form. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshTime(const int64_t formId, const int64_t nextTime); + + /** + * @brief enable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int EnableUpdateForm(const std::vector formIDs, const sptr &callerToken); + + /** + * @brief disable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DisableUpdateForm(const std::vector formIDs, const sptr &callerToken); + + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken); +private: + /** + * @brief Get form configure info. + * @param want The want of the request. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetFormConfigInfo(const Want& want, FormItemInfo &formItemInfo); + /** + * @brief Get bundle info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param packageName Package name. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundleInfo, std::string &packageName); + /** + * @brief Get form info. + * @param want The want of the request. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo); + /** + * @brief Get form configure info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetFormItemInfo(const AAFwk::Want &want, const BundleInfo &bundleInfo, const FormInfo &formInfo, + FormItemInfo &formItemInfo); + /** + * @brief Dimension valid check. + * @param formInfo Form info. + * @param dimensionId Dimension id. + * @return Returns true on success, false on failure. + */ + bool IsDimensionValid(const FormInfo &formInfo, int dimensionId) const; + /** + * @brief Create form configure info. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param itemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode CreateFormItemInfo(const BundleInfo& bundleInfo, const FormInfo& formInfo, FormItemInfo& itemInfo); + /** + * @brief Allocate form by formId. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AllotFormById(const FormItemInfo &info, const sptr &callerToken, + const WantParams &wantParams, FormJsInfo &formInfo); + /** + * @brief Allocate form by form configure info. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AllotFormByInfo(const FormItemInfo &info, const sptr &callerToken, + const WantParams& wantParams, FormJsInfo &formInfo); + /** + * @brief Acquire form data from form provider. + * @param formId The Id of the form.. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AcquireProviderFormInfoAsync(const int64_t formId, const FormItemInfo &info, const WantParams &wantParams); + + /** + * @brief Handle release form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleReleaseForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Handle delete form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleDeleteForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Handle delete temp form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleDeleteTempForm(const int64_t formId, const sptr &callerToken); + + /** + * @brief Handle delete form storage. + * @param dbRecord Form storage information. + * @param uid calling user id. + * @param formId The form id. + * @return Function result and has other host flag. + */ + ErrCode HandleDeleteFormCache(FormRecord &dbRecord, const int uid, const int64_t formId); + + /** + * @brief Padding udid hash. + * @param formId The form id. + * @return Padded form id. + */ + int64_t PaddingUDIDHash(const int64_t formId) const; + + /** + * @brief Add existed form record. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param record Form data. + * @param formId The form id. + * @param wantParams WantParams of the request. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddExistFormRecord(const FormItemInfo &info, const sptr &callerToken, + const FormRecord &record, const int64_t formId, const WantParams &wantParams); + + /** + * @brief Add new form record. + * @param info Form configure info. + * @param formId The form id. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddNewFormRecord(const FormItemInfo &info, const int64_t formId, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo); + + /** + * @brief Send event notify to form provider. The event notify type include FORM_VISIBLE and FORM_INVISIBLE. + * + * @param providerKey The provider key string which consists of the provider bundle name and ability name. + * @param formIdsByProvider The map of form Ids and their event type which have the same provider. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleEventNotify(const std::string &providerKey, const std::vector &formIdsByProvider, + const int32_t formVisibleType); + + /** + * @brief Increase the timer refresh count. + * + * @param formId The form id. + * @return none. + */ + void IncreaseTimerRefreshCount(const int64_t formId); + + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ + int HandleUpdateFormFlag(const std::vector formIds, + const sptr &callerToken, const bool flag); + + /** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ + bool IsFormCached(const FormRecord record); + + /** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshtTimeLocked(const int64_t formId, const int64_t nextTime); + + /** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param bundleName Provider ability bundleName. + * @return Returns true or false. + */ + bool IsUpdateValid(const int64_t formId, const std::string &bundleName); + /** + * @brief Handle cast temp form. + * @param formId The form id. + * @param record Form information. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode HandleCastTempForm(const int64_t formId, const FormRecord &record); + + /** + * @brief Add form timer. + * @param formRecord Form information. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddFormTimer(const FormRecord &formRecord); + + /** + * @brief get bundleName. + * @param bundleName for output. + * @return Returns true on success, others on failure. + */ + bool GetBundleName(std::string &bundleName); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H diff --git a/services/formmgr/include/form_mgr_service.h b/services/formmgr/include/form_mgr_service.h new file mode 100644 index 0000000000000000000000000000000000000000..a2cd4970a0f0153f0eabce755f0f9142331a11ea --- /dev/null +++ b/services/formmgr/include/form_mgr_service.h @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_SERVICE_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_SERVICE_H + +#include +#include +#include +#include +#include +#include + +#include "event_handler.h" +#include "form_mgr_adapter.h" +#include "form_mgr_stub.h" +#include "form_provider_data.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; +/** + * @class FormMgrService + * FormMgrService provides a facility for managing form life cycle. + */ +class FormMgrService : public SystemAbility, + public FormMgrStub, + public std::enable_shared_from_this { + DECLARE_DELAYED_SINGLETON(FormMgrService); + DECLEAR_SYSTEM_ABILITY(FormMgrService); +public: + /** + * @brief Start envent for the form manager service. + */ + void OnStart() override; + /** + * @brief Stop envent for the form manager service. + */ + void OnStop() override; + + /** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + FormJsInfo &formInfo) override; + + /** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int DeleteForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ + int ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) override; + + /** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param FormProviderData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ + int UpdateForm(const int64_t formId, const std::string &bundleName, + const FormProviderData &FormProviderData) override; + + /** + * @brief set next refresh time. + * @param formId The id of the form. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ + int SetNextRefreshTime(const int64_t formId, const int64_t nextTime) override; + + /** + * @brief lifecycle update. + * @param formIds formIds of hostclient. + * @param callerToken Caller ability token. + * @param updateType update type,enable or disable. + * @return Returns true on success, false on failure. + */ + int LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, + const int32_t updateType) override; + + /** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ + int RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) override; + + /** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ + int NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, + const int32_t formVisibleType) override; + + /** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + int CastTempForm(const int64_t formId, const sptr &callerToken) override; + + /** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpStorageFormInfos(std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) override; + /** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ + int DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) override; + + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) override; + + /** + * @brief Check whether if the form manager service is ready. + * @return Returns true if the form manager service is ready; returns false otherwise. + */ + bool IsReady() const; + +private: + /** + * @brief initialization of form manager service. + */ + ErrCode Init(); + + /** + * @brief Permission check by callingUid. + * @param formId the id of the form. + * @return Returns true on success, false on failure. + */ + bool CheckFormPermission(); + + /** + * @brief Permission check. + * @param bundleName bundleName. + * @return Returns true on success, false on failure. + */ + bool CheckFormPermission(const std::string &bundleName) const; +private: + ServiceRunningState state_; + + std::shared_ptr runner_ = nullptr; + std::shared_ptr handler_ = nullptr; + + std::unique_ptr formMgrAdapter_ = nullptr; + + bool resetFlag = false; + + mutable std::mutex instanceMutex_; + + sptr remote = nullptr; + + static const int32_t ENABLE_FORM_UPDATE = 5; + + DISALLOW_COPY_AND_MOVE(FormMgrService); +}; +static bool resetFlag = false; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_SERVICE_H diff --git a/services/formmgr/include/form_msg_event_connection.h b/services/formmgr/include/form_msg_event_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..6fd0981744c3a5e90b1a3d4b4ee00582d907ca58 --- /dev/null +++ b/services/formmgr/include/form_msg_event_connection.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormMsgEventConnection + * Form Refresh Connection Stub. + */ +class FormMsgEventConnection : public FormAbilityConnection { +public: + FormMsgEventConnection(const int64_t formId, const Want &want); + virtual ~FormMsgEventConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormMsgEventConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_provider_mgr.h b/services/formmgr/include/form_provider_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..31e24cee311ccb9706615b666de762141359071b --- /dev/null +++ b/services/formmgr/include/form_provider_mgr.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_MGRR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_MGRR_H +#include +#include +#include "form_provider_info.h" +#include "form_record.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormProviderMgr + * Form provider manager. + */ +class FormProviderMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormProviderMgr) +public: + DISALLOW_COPY_AND_MOVE(FormProviderMgr); + + /** + * @brief handle for acquire back event from provider. + * @param formId The id of the form. + * @param providerFormInfo provider form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AcquireForm(const int64_t formId, const FormProviderInfo &formProviderInfo); + /** + * @brief handle for update form event from provider. + * @param formId The id of the form. + * @param providerFormInfo provider form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateForm(const int64_t formId, const FormProviderInfo &formProviderInfo); + /** + * handle for update form event from provider. + * + * @param formId The id of the form. + * @param formRecord The form's record. + * @param formProviderData provider form info. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode UpdateForm(const int64_t formId, FormRecord &formRecord, const FormProviderData &formProviderData); + /** + * @brief Refresh form. + * + * @param formId The form id. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode RefreshForm(const int64_t formId, const Want &want); + /** + * @brief Connect ams for refresh form + * + * @param formId The form id. + * @param record Form data. + * @param want The want of the form. + * @param isTimerRefresh The flag of timer refresh. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ConnectAmsForRefresh(const int64_t formId, const FormRecord &record, const Want &want, + const bool isTimerRefresh); + /** + * @brief Notify provider form delete. + * @param formId The form id. + * @param record Form information. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode NotifyProviderFormDelete(const int64_t formId, const FormRecord &formRecord); + /** + * @brief Notify provider forms batch delete. + * @param bundleName BundleName. + * @param bundleName AbilityName. + * @param formIds form id list. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode NotifyProviderFormsBatchDelete(const std::string &bundleName, const std::string &abilityName, + const std::set &formIds); + /** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param record Form record. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ + int MessageEvent(const int64_t formId, const FormRecord &record, const Want &want); +private: + FormRecord GetFormAbilityInfo(const FormRecord &record) const; + /** + * @brief Increase the timer refresh count. + * + * @param formId The form id. + */ + void IncreaseTimerRefreshCount(const int64_t formId); + bool IsFormCached(const FormRecord &record); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_MGRR_H \ No newline at end of file diff --git a/services/formmgr/include/form_record.h b/services/formmgr/include/form_record.h new file mode 100644 index 0000000000000000000000000000000000000000..9664003ab6789ad92c968e02c52473eec2788f62 --- /dev/null +++ b/services/formmgr/include/form_record.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_RECORD_H + +#include +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormRecord + * Form data. + */ +class FormRecord { +public: + int64_t formId; + bool isInited = false; + bool needFreeInstall = false; + bool versionUpgrade = false; + bool needRefresh = false; + bool isCountTimerRefresh = false; + std::string packageName; + std::string bundleName; + std::string moduleName; + std::string abilityName; + std::string formName; + int32_t specification; + bool isEnableUpdate; + long updateDuration; + int updateAtHour; + int updateAtMin; + FormProviderInfo formProviderInfo; + std::vector hapSourceDirs; + std::string jsFormCodePath; + bool formTempFlg; + std::vector formUserUids; + bool formVisibleNotify; + int formVisibleNotifyState; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_RECORD_H diff --git a/services/formmgr/include/form_refresh_connection.h b/services/formmgr/include/form_refresh_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..142c06ae99db54408fc76667255359fdc7121cd3 --- /dev/null +++ b/services/formmgr/include/form_refresh_connection.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormRefreshConnection + * Form Refresh Connection Stub. + */ +class FormRefreshConnection : public FormAbilityConnection { +public: + FormRefreshConnection(const int64_t formId, const Want &want); + virtual ~FormRefreshConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormRefreshConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_refresh_limiter.h b/services/formmgr/include/form_refresh_limiter.h new file mode 100644 index 0000000000000000000000000000000000000000..e4202b169b051c383359af0964c782455da5d094 --- /dev/null +++ b/services/formmgr/include/form_refresh_limiter.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_REFRESH_LIMITER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_REFRESH_LIMITER_H + +#include +#include +#include +#include "form_timer.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormRefreshLimiter + * Form refresh limite manager. + */ +class FormRefreshLimiter { +public: + /** + * @brief Add form limit info by formId. + * @param formId The form id. + * @return Returns true on success, false on failure. + */ + bool AddItem(int64_t formId); + /** + * @brief Delete form limit info by formId. + * @param formId The form id. + */ + void DeleteItem(int64_t formId); + /** + * @brief Reset limit info. + */ + void ResetLimit(); + /** + * @brief Refresh enable or not. + * @param formId The form id. + * @return Returns ERR_OK on success, others on failure. + */ + bool IsEnableRefresh(int64_t formId); + /** + * @brief Get refresh count. + * @param formId The form id. + * @return refresh count. + */ + int GetRefreshCount(int64_t formId) const; + /** + * @brief Increase refresh count. + * @param formId The form id. + */ + void Increase(int64_t formId); + /** + * @brief Mark remind flag. + * @param formId The form id. + */ + void MarkRemind(int64_t formId); + /** + * @brief Get remind list. + * @return remind list. + */ + std::vector GetRemindList() const; + /** + * @brief Get remind list and reset limit. + * @return remind list. + */ + std::vector GetRemindListAndResetLimit(); + /** + * @brief Get item count. + * @return Item count. + */ + int GetItemCount() const; +private: + mutable std::mutex limiterMutex_; + std::map limiterMap_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_REFRESH_LIMITER_H \ No newline at end of file diff --git a/services/formmgr/include/form_storage_mgr.h b/services/formmgr/include/form_storage_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..ac3e13e5f3a91aaccfdaa6ebf98730436bc28848 --- /dev/null +++ b/services/formmgr/include/form_storage_mgr.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_STORAGE_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_STORAGE_MGR_H + +#include +#include +#include +#include + +#include "appexecfwk_errors.h" +#include "form_db_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormStorageMgr + * Form data storage. + */ +class FormStorageMgr { +public: + FormStorageMgr() = default; + virtual ~FormStorageMgr() = default; + /** + * @brief Load all form data from DB to innerFormInfos. + * @param innerFormInfos Storage all form data. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode LoadFormData(std::vector &innerFormInfos) const; + + /** + * @brief Get form data from DB to innerFormInfo with formId. + * @param innerFormInfo Storage form data. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) const; + + /** + * @brief Save or update the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be save. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode SaveStorageFormInfo(const InnerFormInfo &innerFormInfo) const; + + /** + * @brief Modify the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo) const; + + /** + * @brief Delete the form data in DB. + * @param formId The form data Id. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DeleteStorageFormInfo(const std::string &formId) const; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_STORAGE_MGR_H diff --git a/services/formmgr/include/form_supply_callback.h b/services/formmgr/include/form_supply_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..031ff49c12bf1e6b5a2c26f5c492c4a40ef1f602 --- /dev/null +++ b/services/formmgr/include/form_supply_callback.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H + +#include "form_ability_connection.h" +#include "form_supply_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyCallback + * form supply service stub. + */ +class FormSupplyCallback : public FormSupplyStub { +public: + FormSupplyCallback() = default; + virtual ~FormSupplyCallback() = default; + static sptr GetInstance(); + + /** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; + + /** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnEventHandle(const Want &want) override; + + /** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ + void AddConnection(sptr connection); + /** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ + void RemoveConnection(long connectId); +private: + static std::mutex mutex_; + static sptr instance_; + + mutable std::mutex conMutex_; + std::map> connections_; + DISALLOW_COPY_AND_MOVE(FormSupplyCallback); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H diff --git a/services/formmgr/include/form_sys_event_receiver.h b/services/formmgr/include/form_sys_event_receiver.h new file mode 100644 index 0000000000000000000000000000000000000000..0706083cf81241e9f9c1056ee1055d1beed97642 --- /dev/null +++ b/services/formmgr/include/form_sys_event_receiver.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_RECEIVER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_RECEIVER_H + +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "form_id_key.h" +#include "form_info.h" +#include "form_record.h" +#include "form_timer.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSysEventReceiver + * Receive system common event. + */ +class FormSysEventReceiver : public EventFwk::CommonEventSubscriber { +public: + FormSysEventReceiver() = default; + FormSysEventReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo); + virtual ~FormSysEventReceiver() = default; + /** + * @brief System common event receiver. + * @param eventData Common event data. + */ + virtual void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; +private: + void HandleProviderUpdated(const std::string &bundleName); + bool ProviderFormUpdated(const int64_t formId, const FormRecord &formRecord, + const std::vector &targetForms); + void HandleProviderRemoved(const std::string &bundleName); + void HandleBundleDataCleared(const std::string &bundleName, const int uid); + void HandleFormHostDataCleared(const int uid); + void ClearFormDBRecordData(const int uid, std::map &removedFormsMap); + void ClearTempFormRecordData(const int uid, std::map &removedFormsMap); + void BatchDeleteNoHostDBForms(const int uid, std::map> &noHostFormDbMap, + std::map &removedFormsMap); + /** + * @brief Delete no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ + void BatchDeleteNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, + std::map &foundFormsMap); + void ReCreateForm(const int64_t formId); + bool IsSameForm(const FormRecord &record, const FormInfo &formInfo); + void GetTimerCfg(const bool updateEnabled, const int updateDuration, const std::string &configUpdateAt, + FormTimerCfg &cfg); + void HandleTimerUpdate(const int64_t formId, const FormRecord &record, const FormTimerCfg &timerCfg); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_PROVIDER_RECEIVER_H \ No newline at end of file diff --git a/services/formmgr/include/form_task_mgr.h b/services/formmgr/include/form_task_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..103e52a84e4d0ab056c3eb5e23bf58a2008ee244 --- /dev/null +++ b/services/formmgr/include/form_task_mgr.h @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TASK_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TASK_MGR_H + +#include +#include + +#include "event_handler.h" +#include "form_item_info.h" +#include "form_js_info.h" +#include "form_provider_info.h" +#include "form_record.h" +#include "ipc_types.h" +#include "iremote_object.h" +#include "form_record.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +using WantParams = OHOS::AAFwk::WantParams; +/** + * @class FormTaskMgr + * form task manager. + */ +class FormTaskMgr final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormTaskMgr) + +public: + DISALLOW_COPY_AND_MOVE(FormTaskMgr); + + /** + * @brief SetEventHandler. + * @param handler event handler + */ + inline void SetEventHandler(const std::shared_ptr &handler) + { + eventHandler_ = handler; + } + + /** + * @brief Acquire form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostAcquireTask(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Delete form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostDeleteTask(const int64_t formId, const Want &want, const sptr &remoteObject); + /** + * @brief Notify provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostProviderBatchDeleteTask(std::set &formIds, const Want &want, + const sptr &remoteObject); + /** + * @brief Refresh form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void PostRefreshTask(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Cast temp form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void PostCastTempTask(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Post form data to form host(task) when acquire form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + + void PostAcquireTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Post form data to form host(task) when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + void PostUpdateTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Handel form host died(task). + * @param remoteHost Form host proxy object. + */ + void PostHostDiedTask(const sptr &remoteHost); + + /** + * @brief Post event notify to form provider. + * + * @param formEvent The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ + void PostEventNotifyTask(const std::vector &formEvent, const int32_t formVisibleType, const Want &want, + const sptr &remoteObject); + + /** + * @brief Post message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void PostFormEventTask(const int64_t formId, const std::string &message, const Want &want, + const sptr &remoteObject); + + /** + * @brief Post uninstall message to form host(task). + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ + void PostUninstallTaskToHost(const std::vector &formIds, const sptr &remoteObject); +private: + /** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void AcquireProviderFormInfo(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Notify form provider for delete form. + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Notify form provider for updating form. + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &remoteObject); + + /** + * @brief Event notify to form provider. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ + void EventNotify(const std::vector &formEvents, const int32_t formVisibleType, const Want &want, + const sptr &remoteObject); + + /** + * @brief Notify form provider for cast temp form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ + void NotifyCastTemp(const int64_t formId, const Want &want, const sptr &remoteObject); + /** + * @brief Post form data to form host when acquire form.. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + void AcquireTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Post form data to form host when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxy object. + */ + void UpdateTaskToHost(const int64_t formId, const FormRecord &record, const sptr &remoteObject); + + /** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ + void HostDied(const sptr &remoteHost); + + /** + * @brief Post provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void ProviderBatchDelete(std::set &formIds, const Want &want, const sptr &remoteObject); + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ + void FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &remoteObject); + + /** + * @brief Handle uninstall message. + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ + void FormUninstall(const std::vector &formIds, const sptr &remoteObject); + + /** + * @brief Create form data for form host. + * @param formId The Id of the form. + * @param record Form record. + * @return Form data. + */ + FormJsInfo CreateFormJsInfo(const int64_t formId, const FormRecord &record); + +private: + std::shared_ptr eventHandler_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TASK_MGR_H diff --git a/services/formmgr/include/form_timer.h b/services/formmgr/include/form_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..94cf7ffcff9b0f6f88bec011eb9cefd3fd16937e --- /dev/null +++ b/services/formmgr/include/form_timer.h @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H +namespace OHOS { +namespace AppExecFwk { +/** + * @enum UpdateType + * Update type. + */ +enum UpdateType { + TYPE_INTERVAL_CHANGE, + TYPE_ATTIME_CHANGE, + TYPE_INTERVAL_TO_ATTIME, + TYPE_ATTIME_TO_INTERVAL, + TYPE_INTERVAL_ONCE, +}; +/** + * @class FormTimer + * form timer task. + */ +class FormTimer { +public: + int64_t formId; + int64_t period; + int hour; + int min; + bool isUpdateAt; + int64_t refreshTime; + bool isEnable = true; + bool isCountTimer = false; + UpdateType type; + + FormTimer() + { + formId = -1; + period = -1; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = false; + } + + FormTimer(int64_t id, bool countTimer) + { + formId = id; + period = -1; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = countTimer; + } + + FormTimer(int64_t id, long repeatTime) + { + formId = id; + period = repeatTime; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = true; + } + + FormTimer(int64_t id, int hourTime, int minTime) + { + formId = id; + hour = hourTime; + min = minTime; + period = -1; + isUpdateAt = true; + isCountTimer = false; + } +}; +/** + * @class UpdateAtItem + * Update item at time. + */ +class UpdateAtItem { +public: + int updateAtTime = -1; + FormTimer refreshTask; +}; +/** + * @class DynamicRefreshItem + * Dynamic refresh item. + */ +class DynamicRefreshItem { +public: + int64_t formId = 0L; + int64_t settedTime = -1L; + + DynamicRefreshItem(){} + + DynamicRefreshItem(int64_t id, int64_t time) + { + formId = id; + settedTime = time; + } +}; +/** + * @struct LimitInfo + * Limit info about a form. + */ +struct LimitInfo { + int refreshCount = 0; + bool isReported = false; + bool remindFlag = false; +}; + +/** + * @struct FormTimerCfg + * Form timer config info. + */ +struct FormTimerCfg { + bool enableUpdate = false; + int64_t updateDuration = 0L; + int updateAtHour = -1; + int updateAtMin = -1; +}; + +// class TimerInfo : public ITimerInfo { +// public: +// TimerInfo(); +// virtual ~TimerInfo(); +// virtual void OnTrigger() override; +// virtual void SetType(const int &type) override; +// virtual void SetRepeat(bool repeat) override; +// virtual void SetInterval(const uint64_t &interval) override; +// virtual void SetWantAgent(std::shared_ptr wantAgent) override; +// void SetCallbackInfo(std::function callBack); + +// private: +// std::function callBack_; +// }; + +// TimerInfo::TimerInfo() +// { +// } + +// TimerInfo::~TimerInfo() +// { +// } + +// void TimerInfo::OnTrigger() +// { +// callBack_(); +// } + +// void TimerInfo::SetCallbackInfo(std::function callBack) +// { +// callBack_ = callBack; +// } + +// void TimerInfo::SetType(const int &_type) +// { +// type = _type; +// } + +// void TimerInfo::SetRepeat(bool _repeat) +// { +// repeat = _repeat; +// } +// void TimerInfo::SetInterval(const uint64_t &_interval) +// { +// interval = _interval; +// } +// void TimerInfo::SetWantAgent(std::shared_ptr _wantAgent) +// { +// wantAgent = _wantAgent; +// } + +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H diff --git a/services/formmgr/include/form_timer_mgr.h b/services/formmgr/include/form_timer_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..b710a2a07995b760074c3c8422bdeeeb6b036a13 --- /dev/null +++ b/services/formmgr/include/form_timer_mgr.h @@ -0,0 +1,317 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_MGR_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_MGR_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "form_refresh_limiter.h" +#include "form_timer.h" + +#include "thread_pool.h" +#include "timer.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormTimerMgr + * form timer task manager. + */ +class FormTimerMgr final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormTimerMgr) +public: + DISALLOW_COPY_AND_MOVE(FormTimerMgr); + /** + * @brief Add form timer by timer task. + * @param task The form timer task. + * @return Returns true on success, false on failure. + */ + bool AddFormTimer(const FormTimer &task); + /** + * @brief Add duration form timer. + * @param formId The Id of the form. + * @param updateDuration Update duration + * @return Returns true on success, false on failure. + */ + bool AddFormTimer(const int64_t formId, const long updateDuration); + /** + * @brief Add scheduled form timer. + * @param formId The Id of the form. + * @param updateAtHour Hour + * @param updateAtMin Min + * @return Returns true on success, false on failure. + */ + bool AddFormTimer(const int64_t formId, const long updateAtHour, const long updateAtMin); + /** + * @brief Remove form timer by form id. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool RemoveFormTimer(const int64_t formId); + /** + * @brief Update form timer. + * @param formId The Id of the form. + * @param type Timer type. + * @param timerCfg Timer config. + * @return Returns true on success, false on failure. + */ + bool UpdateFormTimer(const int64_t formId, const UpdateType &type, const FormTimerCfg &timerCfg); + /** + * @brief Is limiter enable refresh. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool IsLimiterEnableRefresh(const int64_t formId); + /** + * @brief Increase refresh count. + * @param formId The Id of the form. + */ + void IncreaseRefreshCount(const int64_t formId); + /** + * @brief Set next refresh time. + * @param formId The Id of the form. + * @param nextGapTime Next gap time. + * @return Returns true on success, false on failure. + */ + bool SetNextRefreshTime(const int64_t formId, const long nextGapTime); + /** + * @brief Get refresh count. + * @param formId The Id of the form. + * @return Returns refresh count. + */ + int GetRefreshCount(const int64_t formId) const; + /** + * @brief Mark remind. + * @param formId The Id of the form. + * @return true or false. + */ + void MarkRemind(const int64_t formId); + + /** + * @brief Handle system time changed. + */ + void HandleSystemTimeChanged(); + /** + * @brief Reset form limiter. + */ + void HandleResetLimiter(); + /** + * @brief Update attime trigger. + * @param updateTime Update time. + */ + void OnUpdateAtTrigger(long updateTime); + /** + * @brief Dynamic time trigger. + * @param updateTime Update time. + */ + void OnDynamicTimeTrigger(long updateTime); + +private: + /** + * @brief Add update at timer. + * @param task Update time task. + * @return Returns true on success, false on failure. + */ + bool AddUpdateAtTimer(const FormTimer &task); + /** + * @brief Add update at timer item. + * @param task Update at timer item. + */ + void AddUpdateAtItem(const UpdateAtItem &atItem); + /** + * @brief Add update interval timer task. + * @param task Update interval timer task. + * @return Returns true on success, false on failure. + */ + bool AddIntervalTimer(const FormTimer &task); + /** + * @brief interval timer task timeout. + */ + void OnIntervalTimeOut(); + /** + * @brief Get remind tasks. + * @param remindTasks Remind tasks. + * @return Returns true on success, false on failure. + */ + bool GetRemindTasks(std::vector &remindTasks); + /** + * @brief Set enableFlag for interval timer task. + * @param formId The Id of the form. + * @param flag Enable flag. + */ + void SetIntervalEnableFlag(int64_t formId, bool flag); + /** + * @brief Update Interval timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool UpdateIntervalValue(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Update update at timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool UpdateAtTimerValue(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Interval timer task to update at timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool IntervalToAtTimer(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Update at timer task to interval timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ + bool AtTimerToIntervalTimer(const int64_t formId, const FormTimerCfg &timerCfg); + /** + * @brief Delete interval timer task. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool DeleteIntervalTimer(const int64_t formId); + /** + * @brief Delete update at timer. + * @param formId The Id of the form. + */ + void DeleteUpdateAtTimer(const int64_t formId); + /** + * @brief Update at timer task alarm. + * @return Returns true on success, false on failure. + */ + bool UpdateAtTimerAlarm(); + /** + * @brief Update limiter task alarm. + * @return Returns true on success, false on failure. + */ + bool UpdateLimiterAlarm(); + /** + * @brief Delete dynamic refresh item. + * @param formId The Id of the form. + */ + void DeleteDynamicItem(const int64_t formId); + /** + * @brief Update dynamic refresh task alarm. + * @return Returns true on success, false on failure. + */ + bool UpdateDynamicAlarm(); + /** + * @brief Clear dynamic refresh resource. + */ + void ClearDynamicResource(); + /** + * @brief Fint next at timer item. + * @param nowTime Update time. + * @param updateAtItem Next at timer item. + * @return Returns true on success, false on failure. + */ + bool FindNextAtTimerItem(const int nowTime, UpdateAtItem &updateAtItem); + /** + * @brief Clear update at timer resource. + */ + void ClearUpdateAtTimerResource(); + + /** + * @brief Execute Form timer task. + * @param task Form timer task. + */ + void ExecTimerTask(const FormTimer &task); + + /** + * @brief Init. + */ + void Init(); + /** + * @brief Ensure init interval timer resource. + */ + void EnsureInitIntervalTimer(); + /** + * @brief Clear interval timer resource. + */ + void ClearIntervalTimer(); + /** + * @brief Get thread pool for timer task. + */ + OHOS::ThreadPool* GetTaskThreadExecutor(); + + /** + * @brief Set enable flag. + * @param formId The Id of the form. + * @param flag Enable flag. + */ + void SetEnableFlag(int64_t formId, bool flag); +private: + /** + * @class TimerReceiver + * timer event receiver. + */ + class TimerReceiver : public EventFwk::CommonEventSubscriber { + public: + TimerReceiver() = default; + TimerReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo); + virtual ~TimerReceiver() = default; + /** + * @brief Receive common event. + * @param eventData Common event data. + */ + virtual void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; + }; + + struct { + bool operator()(DynamicRefreshItem a, DynamicRefreshItem b) const + { + return (a.settedTime > b.settedTime ? true : false); + } + } CompareDynamicRefreshItem; + + mutable std::mutex intervalMutex_; + mutable std::mutex updateAtMutex_; + mutable std::mutex dynamicMutex_; + mutable std::mutex refreshMutex_; + FormRefreshLimiter refreshLimiter_; + std::map intervalTimerTasks_; + std::list updateAtTimerTasks_; + std::vector dynamicRefreshTasks_; + + std::shared_ptr timerReceiver_; + + OHOS::ThreadPool* taskExecutor_; + Utils::Timer* intervalTimer_; + + long dynamicWakeUpTime_ = LONG_MAX; + long atTimerWakeUpTime_ = LONG_MAX; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_MGR_H diff --git a/services/formmgr/include/form_util.h b/services/formmgr/include/form_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d043693889bcbd385f65318a8998f27ed0b7e056 --- /dev/null +++ b/services/formmgr/include/form_util.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormUtil + * form utils. + */ +class FormUtil { +public: + /** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ + static void CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, + Want &want); + /** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param userId user id. + */ + static void CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t userId); + + /** + * @brief create udid for form. + * @return udid. + */ + static std::string GenerateUdid(); + + /** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ + static int64_t GenerateFormId(int64_t udidHash); + + /** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash. + * @return new form id. + */ + static int64_t PaddingUDIDHash(int64_t formId, int64_t udidHash); + + /** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ + static bool GenerateUdidHash(int64_t &udidHash); + /** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ + static long GetCurrentNanosecond(); + /** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ + static long GetCurrentMillisecond(); + /** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ + static long GetMillisecondFromTm(struct tm &tmAtTime); + + /** + * @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ + static std::vector StringSplit(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H \ No newline at end of file diff --git a/services/formmgr/src/form_ability_connection.cpp b/services/formmgr/src/form_ability_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a22a38647e50b646065cf56191565f31bdb9a60 --- /dev/null +++ b/services/formmgr/src/form_ability_connection.cpp @@ -0,0 +1,102 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ability_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAbilityConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}lld, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + // deviceId_ = element.GetDeviceID(); + // bundleName_ = element.GetBundleName(); + // abilityName_ = element.GetAbilityName(); + + if (isFreeInstall_) { + // Handle free install for form provider app + } +} +/** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + APP_LOGD("%{public}s, element:%{public}s, resultCode:%{public}d", __func__, element.GetURI().c_str(), resultCode); + if (connectId_ > 0) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId_); + } else { + APP_LOGE("%{public}s fail, connectId_ invalidate. connectId_: %{public}ld", __func__, connectId_); + } +} + +/** + * @brief Remote object died event. + * @param remoteObject the remote object of service ability. + */ +void FormAbilityConnection::OnConnectDied(const wptr &remoteObject) +{ + if (connectId_ > 0) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId_); + } else { + APP_LOGE("%{public}s fail, connectId_ invalidate. connectId_: %{public}ld", __func__, connectId_); + } +} +/** + * @brief Set connectId. + * @param connectId The ability connection id. + */ +void FormAbilityConnection::SetConnectId(long connectId) +{ + APP_LOGI("%{public}s, connectId_: %{public}ld", __func__, connectId); + connectId_ = connectId; +} +/** + * @brief Get connectId. + * @return The ability connection id. + */ +long FormAbilityConnection::GetConnectId() +{ + return connectId_; +} +// std::string FormAbilityConnection::GetProviderKey() +// { +// if(deviceId_.empty() || bundleName_.empty() || abilityName_.empty()) { +// return ""; +// } +// return deviceId_ + "::" + bundleName_ + "::" + abilityName_; +// } +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_acquire_connection.cpp b/services/formmgr/src/form_acquire_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a6a765285edbcffa96642bf73c11c2b2c059b69 --- /dev/null +++ b/services/formmgr/src/form_acquire_connection.cpp @@ -0,0 +1,65 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_acquire_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormAcquireConnection::FormAcquireConnection(const int64_t formId, const FormItemInfo &info, +const WantParams &wantParams) + :formId_(formId), + info_(info), + wantParams_(wantParams) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAcquireConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}lld, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + Want want; + want.SetParams(wantParams_); + FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); + if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + } else { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + } + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_ams_helper.cpp b/services/formmgr/src/form_ams_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a393c4aa0e349f92c51a56f9bc7fd85f5a0719d --- /dev/null +++ b/services/formmgr/src/form_ams_helper.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2021 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 "ability_manager_interface.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ams_helper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +FormAmsHelper::FormAmsHelper(){} +FormAmsHelper::~FormAmsHelper(){} + +/** + * @brief acquire a form ability manager, if it not existed, + * @return returns the ability manager ipc object, or nullptr for failed. + */ +sptr FormAmsHelper::GetAbilityManager() +{ + if (abilityManager_ == nullptr) { + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + APP_LOGE("%{public}s:fail to get registry", __func__); + return nullptr; + } + sptr remoteObject = systemManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + APP_LOGE("%{public}s:fail to connect AbilityMgrService", __func__); + return nullptr; + } + APP_LOGD("connect AbilityMgrService success"); + + abilityManager_ = iface_cast(remoteObject); + } + + return abilityManager_; +} + +/** + * @brief ConnectAbility, connect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormAmsHelper::ConnectServiceAbility( + const Want &want, const sptr &connect) +{ + APP_LOGI("%{public}s called.", __func__); + sptr ams = GetAbilityManager(); + if (ams == nullptr) { + APP_LOGE("%{public}s:ability service not connect", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ams->ConnectAbility(want, connect, nullptr); +} +/** + * @brief DisConnectAbility, disconnect session with service ability. + * @param want Special want for service type's ability. + * @param connect Callback used to notify caller the result of connecting or disconnecting. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormAmsHelper::DisConnectServiceAbility(const sptr &connect) +{ + sptr ams = GetAbilityManager(); + if (ams == nullptr) { + APP_LOGE("%{public}s:ability service not connect", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ams->DisconnectAbility(connect); +} +/** + * @brief Add the ability manager instance for debug. + * @param abilityManager the ability manager ipc object. + */ +void FormAmsHelper::SetAbilityManager(const sptr &abilityManager) +{ + abilityManager_ = abilityManager; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_batch_delete_connection.cpp b/services/formmgr/src/form_batch_delete_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6da3a394eac36c6415e258d88a4a613fc7d020d0 --- /dev/null +++ b/services/formmgr/src/form_batch_delete_connection.cpp @@ -0,0 +1,55 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_batch_delete_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormBatchDeleteConnection::FormBatchDeleteConnection(const std::set &formIds) + :formIds_(formIds) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormBatchDeleteConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostProviderBatchDeleteTask(formIds_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_bms_helper.cpp b/services/formmgr/src/form_bms_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22180d22631947ba5e665089e42185fe9b17df52 --- /dev/null +++ b/services/formmgr/src/form_bms_helper.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2021 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 "ability_manager_interface.h" +#include "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_bms_helper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +FormBmsHelper::FormBmsHelper() +{} + +FormBmsHelper::~FormBmsHelper() +{} + +/** + * @brief Acquire a bundle manager, if it not existed. + * @return returns the bundle manager ipc object, or nullptr for failed. + */ +sptr FormBmsHelper::GetBundleMgr() +{ + APP_LOGI("%{public}s called.", __func__); + + if (iBundleMgr_ == nullptr) { + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + APP_LOGE("%{public}s error, failed to get bundle manager service.", __func__); + return nullptr; + } + + iBundleMgr_ = iface_cast(remoteObject); + if (iBundleMgr_ == nullptr) { + APP_LOGE("%{public}s error, failed to get bundle manager service", __func__); + return nullptr; + } + } + return iBundleMgr_; +} + +/** + * @brief Add the bundle manager instance for debug. + * @param bundleManager the bundle manager ipc object. + */ +void FormBmsHelper::SetBundleManager(const sptr &bundleManager) +{ + APP_LOGI("%{public}s called.", __func__); + + iBundleMgr_ = bundleManager; +} +/** + * @brief Notify module removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ +void FormBmsHelper::NotifyModuleRemovable(const std::string &bundleName, const std::string &moduleName) +{ + APP_LOGI("%{public}s, bundleName:%{public}s, moduleName:%{public}s", __func__, bundleName.c_str(), + moduleName.c_str()); + if (bundleName.empty() || moduleName.empty()) { + return; + } + + std::string key = GenerateModuleKey(bundleName, moduleName); + APP_LOGI("%{public}s, begin to notify %{public}s removable", __func__, key.c_str()); + sptr iBundleMgr = GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s, failed to get IBundleMgr.", __func__); + return; + } + + std::string originId = IPCSkeleton::ResetCallingIdentity(); + // iBundleMgr->UpdateModuleRemovableFlag(bundleName, moduleName, FLAG_MODULE_NOT_USED_BY_FORM); + + IPCSkeleton::SetCallingIdentity(originId); +} +/** + * @brief Notify module not removable. + * @param bundleName Provider ability bundleName. + * @param moduleName Provider ability moduleName. + */ +void FormBmsHelper::NotifyModuleNotRemovable(const std::string &bundleName, const std::string &moduleName) const +{ + std::string key = GenerateModuleKey(bundleName, moduleName); + APP_LOGI("%{public}s, begin to notify %{public}s not removable", __func__, key.c_str()); +} + +std::string FormBmsHelper::GenerateModuleKey(const std::string &bundleName, const std::string &moduleName) const +{ + return bundleName + "#" + moduleName; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_cache_mgr.cpp b/services/formmgr/src/form_cache_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..002f41b9da8997c3f051abb63f54355c0f6a31aa --- /dev/null +++ b/services/formmgr/src/form_cache_mgr.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_cache_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +FormCacheMgr::FormCacheMgr() +{ + APP_LOGI("create form cache manager instance"); +} +FormCacheMgr::~FormCacheMgr() +{ + APP_LOGI("destroy form cache manager instance"); +} + +/** + * @brief Get form data. + * @param formId, Form id. + * @param data, Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::GetData(const int64_t formId, std::string &data) const +{ + APP_LOGI("get cache data"); + std::lock_guard lock(cacheMutex_); + if (cacheData_.empty()) { + APP_LOGE("form cache is empty"); + return false; + } + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGE("cache data not find"); + return false; + } + + data = formData->second; + + return true; +} + +/** + * @brief Add form data. + * @param formId, Form id. + * @param data, Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::AddData(const int64_t formId, const std::string &data) +{ + APP_LOGI("add new cache data"); + std::lock_guard lock(cacheMutex_); + std::pair::iterator, bool> retVal + = cacheData_.emplace(formId, data); + + return retVal.second; +} + +/** + * @brief Delete form data. + * @param formId, Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::DeleteData(const int64_t formId) +{ + APP_LOGI("delete cache data"); + std::lock_guard lock(cacheMutex_); + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGW("cache data is not exist"); + return true; + } + + return cacheData_.erase(formId); +} + +/** + * @brief Update form data. + * @param formId, Form id. + * @param data, Cache data. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::UpdateData(const int64_t formId, const std::string &data) +{ + APP_LOGI("update cache data"); + std::lock_guard lock(cacheMutex_); + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGE("cache data is not exist"); + return false; + } + + formData->second = data; + return true; +} +/** + * @brief Check if form data is exist or not. + * @param formId, Form id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormCacheMgr::IsExist(const int64_t formId) const +{ + APP_LOGI("get cache data"); + std::lock_guard lock(cacheMutex_); + if (cacheData_.empty()) { + APP_LOGE("form cache is empty"); + return false; + } + auto formData = cacheData_.find(formId); + if (formData == cacheData_.end()) { + APP_LOGE("cache data not find"); + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_cast_temp_connection.cpp b/services/formmgr/src/form_cast_temp_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1c46519cd1d541ccab96df2cbbc3754b57bceaf --- /dev/null +++ b/services/formmgr/src/form_cast_temp_connection.cpp @@ -0,0 +1,54 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_cast_temp_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" + +namespace OHOS { +namespace AppExecFwk { +FormCastTempConnection::FormCastTempConnection(const int64_t formId) + :formId_(formId) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormCastTempConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}lld, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostCastTempTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_data_mgr.cpp b/services/formmgr/src/form_data_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a3518a81f86fc35bf2d0fbd85ab1b48fb43b148 --- /dev/null +++ b/services/formmgr/src/form_data_mgr.cpp @@ -0,0 +1,1126 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_cache_mgr.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_provider_mgr.h" +#include "form_util.h" +#include "ipc_skeleton.h" + + +namespace OHOS { +namespace AppExecFwk { +FormDataMgr::FormDataMgr() +{ + APP_LOGI("create form data manager instance"); + udidHash_ = 0L; +} +FormDataMgr::~FormDataMgr() +{ + APP_LOGI("destroy form data manager instance"); +} + +/** + * @brief Delete form js info by form record. + * @return Returns all form records map. + */ +std::map& FormDataMgr::GetAllFormRecord() +{ + return formRecords_; +} + +/** + * @brief Get all form client host record. + * @return Returns all form client host record. + */ +std::vector& FormDataMgr::GetClientRecords() +{ + return clientRecords_; +} + +/** + * @brief Get all form host records. + * @return Returns all form host records vector. + */ +std::vector& FormDataMgr::GetAllFormHostRecord() +{ + return clientRecords_; +} +/** + * @brief Allot form info by item info. + * @param formId The Id of the form. + * @param formInfo Form item info. + * @param callingUid The UID of the proxy. + * @return Returns form record. + */ +FormRecord FormDataMgr::AllotFormRecord(const FormItemInfo &formInfo, const int callingUid) +{ + APP_LOGI("%{public}s, allot form info", __func__); + if (formInfo.IsTemporaryForm() && !ExistTempForm(formInfo.GetFormId())) { + std::lock_guard lock(formTempMutex_); + tempForms_.emplace_back(formInfo.GetFormId()); + } + FormRecord record; + { + std::lock_guard lock(formRecordMutex_); + if (formRecords_.empty()) { // formRecords_ is empty, create a new one + APP_LOGD("%{public}s, form info not exist", __func__); + record = CreateFormRecord(formInfo, callingUid); + formRecords_.emplace(formInfo.GetFormId(), record); + } else { + auto info = formRecords_.find(formInfo.GetFormId()); + if (info == formRecords_.end()) { + APP_LOGD("%{public}s, form info not find", __func__); + record = CreateFormRecord(formInfo, callingUid); + formRecords_.emplace(formInfo.GetFormId(), record); + } else { + record = info->second; + } + } + } + APP_LOGI("%{public}s end", __func__); + return record; +} +/** + * @brief Delete form js info by form record. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteFormRecord(const int64_t formId) { + APP_LOGI("%{public}s, delete form info", __func__); + std::lock_guard lock(formRecordMutex_); + auto iter = formRecords_.find(formId); + if (iter == formRecords_.end()) { + APP_LOGE("%{public}s, form info is not exist", __func__); + return true; + } + formRecords_.erase(iter); + return true; +} +/** + * @brief Allot form host record by caller token. + * @param info The form item info. + * @param callerToken callerToken + * @param formId The Id of the form. + * @param callingUid The UID of the proxy. + * @param record Form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::AllotFormHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int64_t formId, const int callingUid) +{ + APP_LOGI("%{public}s, allot form Host info", __func__); + std::lock_guard lock(formHostRecordMutex_); + for (auto &record : clientRecords_) { + if (callerToken == record.GetClientStub()) { + record.AddForm(formId); + APP_LOGI("%{public}s end", __func__); + return true; + } + } + FormHostRecord hostRecord; + bool isCreated = CreateHostRecord(info, callerToken, callingUid, hostRecord); + if (isCreated) { + hostRecord.AddForm(formId); + clientRecords_.emplace_back(hostRecord); + APP_LOGI("%{public}s end", __func__); + return true; + } + APP_LOGI("%{public}s end", __func__); + return false; +} +/** + * @brief Create host record. + * @param info The form item info. + * @param callerToken The UID of the proxy. + * @param callingUid The UID of the proxy. + * @param record The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::CreateHostRecord(const FormItemInfo &info, const sptr &callerToken, + const int callingUid, FormHostRecord& record) { + if (callerToken == nullptr) { + APP_LOGE("%{public}s, invalid param", __func__); + return false; + } + + record = FormHostRecord::CreateRecord(info, callerToken, callingUid); + return true; +} +/** + * @brief Create form record. + * @param formInfo The form item info. + * @param callingUid The UID of the proxy. + * @return Form record. + */ +FormRecord FormDataMgr::CreateFormRecord(const FormItemInfo &formInfo, const int callingUid) const +{ + APP_LOGI("%{public}s, create form info", __func__); + FormRecord newRecord; + newRecord.formId = formInfo.GetFormId(); + newRecord.packageName = formInfo.GetPackageName(); + newRecord.bundleName = formInfo.GetProviderBundleName(); + newRecord.moduleName = formInfo.GetModuleName(); + newRecord.abilityName = formInfo.GetAbilityName(); + newRecord.formName = formInfo.GetFormName(); + newRecord.specification = formInfo.GetSpecificationId(); + newRecord.isEnableUpdate = formInfo.IsEnableUpdateFlag(); + newRecord.formTempFlg = formInfo.IsTemporaryForm(); + newRecord.formVisibleNotify = formInfo.IsFormVisibleNotify(); + newRecord.jsFormCodePath = formInfo.GetHapSourceByModuleName(newRecord.moduleName); + if (newRecord.isEnableUpdate) { + ParseUpdateConfig(newRecord, formInfo); + } + if (std::find(newRecord.formUserUids.begin(), newRecord.formUserUids.end(), + callingUid) == newRecord.formUserUids.end()) { + newRecord.formUserUids.emplace_back(callingUid); + } + + formInfo.GetHapSourceDirs(newRecord.hapSourceDirs); + APP_LOGI("%{public}s end", __func__); + return newRecord; +} +/** + * @brief Create form js info by form record. + * @param formId The Id of the form. + * @param record Form record. + * @param formInfo Js info. + * @return None. + */ +void FormDataMgr::CreateFormInfo(const int64_t formId, const FormRecord &record, FormJsInfo &formInfo) +{ + formInfo.formId = formId; + formInfo.bundleName = record.bundleName; + formInfo.abilityName = record.abilityName; + formInfo.formName = record.formName; + formInfo.formTempFlg = record.formTempFlg; + // formInfo.setInstantProvider(record.instantProvider); +} +/** + * @brief Check temp form count is max. + * @return Returns ERR_OK if the temp form not reached; returns ERR_MAX_SYSTEM_TEMP_FORMS is reached. + */ +int FormDataMgr::CheckTempEnoughForm() const +{ + if (tempForms_.size() >= Constants::MAX_TEMP_FORMS) { + APP_LOGW("%{public}s, already exist %{public}d temp forms in system", __func__, Constants::MAX_TEMP_FORMS); + // HiViewUtil.sendAddFormExceedLimitEvent(); + return ERR_MAX_SYSTEM_TEMP_FORMS; + } + return ERR_OK; +} +/** + * @brief Check form count is max. + * @param callingUid The UID of the proxy. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +int FormDataMgr::CheckEnoughForm(const int callingUid) const +{ + APP_LOGI("%{public}s, callingUid: %{public}d", __func__, callingUid); + + if (formRecords_.size() - tempForms_.size() >= Constants::MAX_FORMS) { + APP_LOGW("%{public}s, already exist %{public}d forms in system", __func__, Constants::MAX_FORMS); + return ERR_MAX_SYSTEM_FORMS; + } + + int callingUidFormCounts = 0; + for (auto &recordPair : formRecords_) { + FormRecord record = recordPair.second; + if (IsCallingUidValid(record.formUserUids) && !record.formTempFlg) { + for (auto &userUid : record.formUserUids) { + if (userUid == callingUid) { + if (++callingUidFormCounts >= Constants::MAX_RECORD_PER_APP) + { + APP_LOGW("%{public}s, already use %{public}d forms", __func__, Constants::MAX_RECORD_PER_APP); + return ERR_MAX_RECORDS_PER_APP; + } + } + } + } + } + return ERR_OK; +} +/** + * @brief Delete temp form. + * @param formId The Id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteTempForm(const int64_t formId) +{ + std::lock_guard lock(formTempMutex_); + auto iter = std::find(tempForms_.begin(), tempForms_.end(), formId); + if (iter == tempForms_.end()) { + APP_LOGE("%{public}s, temp form is not exist", __func__); + return true; + } + tempForms_.erase(iter); + return true; +} +/** + * @brief Check temp form is exist. + * @param formId The Id of the form. + * @return Returns true if the temp form is exist; returns false is not exist. + */ +bool FormDataMgr::ExistTempForm(const int64_t formId) const +{ + return (std::find(tempForms_.begin(), tempForms_.end(), formId) != tempForms_.end()); +} +/** + * @brief Check calling uid is valid. + * @param formUserUids The form user uids. + * @return Returns true if this user uid is valid; returns false otherwise. + */ +bool FormDataMgr::IsCallingUidValid(const std::vector &formUserUids) const +{ + if (formUserUids.size() != 0) { + for (auto &userUid : formUserUids) { + if (userUid == IPCSkeleton::GetCallingUid()) { + return true; + } + } + } + return false; +} +/** + * @brief Modify form temp flag by formId. + * @param formId The Id of the form. + * @param formTempFlg The form temp flag. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::ModifyFormTempFlg(const int64_t formId, const bool formTempFlg) +{ + APP_LOGI("%{public}s, modify form temp flag by formId", __func__); + std::lock_guard lock(formRecordMutex_); + if (!ExistFormRecord(formId)) { + APP_LOGE("%{public}s, form info is not exist", __func__); + return false; + } + formRecords_[formId].formTempFlg = formTempFlg; + return true; +} +/** + * @brief Add form user uid from form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::AddFormUserUid(const int64_t formId, const int32_t formUserUid) +{ + APP_LOGI("%{public}s, add form user uid by formId", __func__); + std::lock_guard lock(formRecordMutex_); + if (!ExistFormRecord(formId)) { + APP_LOGE("%{public}s, form info is not exist", __func__); + return false; + } + if (std::find(formRecords_[formId].formUserUids.begin(), formRecords_[formId].formUserUids.end(), + formUserUid) == formRecords_[formId].formUserUids.end()) { + formRecords_[formId].formUserUids.emplace_back(formUserUid); + } + return true; +} +/** + * @brief Delete form user uid from form record. + * @param formId The Id of the form. + * @param uid calling user id. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteFormUserUid(const int64_t formId, const int32_t uid) +{ + APP_LOGI("%{public}s, delete form user uid from form record", __func__); + std::lock_guard lock(formRecordMutex_); + if (ExistFormRecord(formId)) { + auto iter = std::find(formRecords_.at(formId).formUserUids.begin(), formRecords_.at(formId).formUserUids.end(), + uid); + if (iter != formRecords_.at(formId).formUserUids.end()) { + formRecords_.at(formId).formUserUids.erase(iter); + } + return true; + } else { + APP_LOGE("%{public}s, form info not find", __func__); + return false; + } +} +/** + * @brief Update form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::UpdateFormRecord(const int64_t formId, const FormRecord &formRecord) +{ + APP_LOGI("%{public}s, get form record by formId", __func__); + std::lock_guard lock(formRecordMutex_); + auto info = formRecords_.find(formId); + if (info != formRecords_.end()) { + formRecords_[formId] = formRecord; + return true; + } + return false; +} +/** + * @brief Get form record. + * @param formId The Id of the form. + * @param formRecord The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GetFormRecord(const int64_t formId, FormRecord &formRecord) const +{ + APP_LOGI("%{public}s, get form record by formId", __func__); + std::lock_guard lock(formRecordMutex_); + auto info = formRecords_.find(formId); + if (info == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return false; + } + formRecord = info->second; + + APP_LOGI("%{public}s, get form record successfully", __func__); + return true; +} +/** + * @brief Get form record. + * @param bundleName Bundle name. + * @param formInfos The form record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GetFormRecord(const std::string &bundleName, std::vector &formInfos) +{ + APP_LOGI("%{public}s, get form record by bundleName", __func__); + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + if (bundleName == itFormRecord->second.bundleName) { + formInfos.emplace_back(itFormRecord->second); + } + } + if (formInfos.size() > 0) { + return true; + } else { + APP_LOGI("%{public}s, form info not find", __func__); + return false; + } +} +/** + * @brief Check form record is exist. + * @param formId The Id of the form. + * @return Returns true if the form record is exist; returns false is not exist. + */ +bool FormDataMgr::ExistFormRecord(const int64_t formId) const +{ + APP_LOGI("%{public}s, check form record is exist", __func__); + return (formRecords_.count(formId) > 0); +} +/** + * @brief Has form user uids in form record. + * @param formId The Id of the form. + * @return Returns true if this form has form user uids; returns false is not has. + */ +bool FormDataMgr::HasFormUserUids(const int64_t formId) const +{ + APP_LOGI("%{public}s, check form has user uids", __func__); + FormRecord record; + if (GetFormRecord(formId, record)) { + return record.formUserUids.empty() ? false : true; + } + return false; +} +/** + * @brief Get form host record. + * @param formId The id of the form. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GetFormHostRecord(const int64_t formId, FormHostRecord &formHostRecord) const +{ + APP_LOGI("%{public}s, get form host record by formId", __func__); + std::lock_guard lock(formHostRecordMutex_); + for (auto &record : clientRecords_) { + if (record.Contains(formId)) { + formHostRecord = record; + return true; + } + } + + APP_LOGE("%{public}s, form host record not find", __func__); + return false; +} +/** + * @brief Delete form host record. + * @param callerToken The client stub of the form host record. + * @param formId The id of the form. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::DeleteHostRecord(const sptr &callerToken, const int64_t formId) +{ + APP_LOGI("%{public}s start, delete form host record", __func__); + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator iter; + for (iter = clientRecords_.begin(); iter != clientRecords_.end(); ++iter) { + if (callerToken == iter->GetClientStub()) { + iter->DelForm(formId); + if (iter->IsEmpty()) { + iter->CleanResource(); + iter = clientRecords_.erase(iter); + } + break; + } + } + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Clean removed forms form host. + * @param removedFormIds The id list of the forms. + */ +void FormDataMgr::CleanHostRemovedForms(const std::vector &removedFormIds) +{ + APP_LOGI("%{public}s start, delete form host record by formId list", __func__); + std::vector matchedIds; + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + for (const int64_t& formId : removedFormIds) { + if (itHostRecord->Contains(formId)) { + matchedIds.emplace_back(formId); + itHostRecord->DelForm(formId); + } + } + if (!matchedIds.empty()) { + APP_LOGI("%{public}s, OnFormUninstalled called", __func__); + itHostRecord->OnFormUninstalled(matchedIds); + } + } + + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ +void FormDataMgr::HandleHostDied(const sptr &remoteHost) +{ + std::vector recordTempForms; + { + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { + if (remoteHost == itHostRecord->GetClientStub()) { + HandleHostDiedForTempForms(*itHostRecord, recordTempForms); + APP_LOGI("find died client, remove it"); + itHostRecord->CleanResource(); + itHostRecord = clientRecords_.erase(itHostRecord); + break; + } else { + itHostRecord++; + } + } + } + { + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + int64_t formId = itFormRecord->first; + // if temp form, remove it + if (std::find(recordTempForms.begin(), recordTempForms.end(), formId) != recordTempForms.end()) { + FormRecord formRecord = itFormRecord->second; + itFormRecord = formRecords_.erase(itFormRecord); + FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, formRecord); + } else { + itFormRecord++; + } + } + } +} + +/** + * @brief Get the temp forms from host and delete temp form in cache. + * @param record The form record. + * @param recordTempForms Getted the temp forms. + */ +void FormDataMgr::HandleHostDiedForTempForms(const FormHostRecord &record, std::vector &recordTempForms) +{ + std::lock_guard lock(formTempMutex_); + std::vector::iterator itForm; + for (itForm = tempForms_.begin(); itForm != tempForms_.end();) { + if (record.Contains(*itForm)) { + recordTempForms.emplace_back(*itForm); + itForm = tempForms_.erase(itForm); + } else { + itForm++; + } + } +} + +/** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable. + */ +bool FormDataMgr::IsEnableRefresh(int64_t formId) +{ + std::lock_guard lock(formHostRecordMutex_); + for (auto &record : clientRecords_) { + if (record.IsEnableRefresh(formId)) { + return true; + } + } + + return false; +} +/** + * @brief Generate form id. + * @return form id. + */ +int64_t FormDataMgr::GenerateFormId() +{ + return FormUtil::GenerateFormId(udidHash_); +} +/** + * @brief Generate udid. + * @return Returns true if this function is successfully called; returns false otherwise. + */ +bool FormDataMgr::GenerateUdidHash() +{ + if (udidHash_ != Constants::INVALID_UDID_HASH) { + return true; + } + + bool bGenUdid = FormUtil::GenerateUdidHash(udidHash_); + if (!bGenUdid) { + APP_LOGE("%{public}s, Failed to generate udid.", __func__); + return false; + } + + return true; +} +/** + * @brief Get udid. + * @return udid. + */ +int64_t FormDataMgr::GetUdidHash() const +{ + return udidHash_; +} +/** + * @brief Set udid. + * @param udidHash udid. + */ +void FormDataMgr::SetUdidHash(const int64_t udidHash) +{ + udidHash_ = udidHash; +} + +/** + * @brief Get the matched form host record by client stub. + * + * @param callerToken The client stub of the form host record. + * @param formHostRecord The form host record. + * @return Returns true if this function is successfully called, returns false otherwise. + */ +bool FormDataMgr::GetMatchedHostClient(const sptr &callerToken, FormHostRecord &formHostRecord) const +{ + APP_LOGI("%{public}s, get the matched form host record by client stub.", __func__); + std::lock_guard lock(formHostRecordMutex_); + for (const FormHostRecord &record : clientRecords_) { + if (callerToken == record.GetClientStub()) { + formHostRecord = record; + return true; + } + } + + APP_LOGE("%{public}s, form host record not find.", __func__); + return false; +} + +/** + * @brief Set needRefresh for FormRecord. + * @param formId The Id of the form. + * @param needRefresh true or false. + */ +void FormDataMgr::SetNeedRefresh(const int64_t formId, const bool needRefresh) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.needRefresh = needRefresh; +} + +/** + * @brief Set isCountTimerRefresh for FormRecord. + * @param formId The Id of the form. + * @param countTimerRefresh true or false. + */ +void FormDataMgr::SetCountTimerRefresh(const int64_t formId, const bool countTimerRefresh) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.isCountTimerRefresh = countTimerRefresh; +} + +/** + * @brief Get updated form. + * @param record FormRecord. + * @param targetForms Target forms. + * @param updatedForm Updated formnfo. + * @return Returns true on success, false on failure. + */ +bool FormDataMgr::GetUpdatedForm(const FormRecord &record, const std::vector &targetForms, +FormInfo &updatedForm) +{ + if (targetForms.empty()) { + APP_LOGE("%{public}s error, targetForms is empty.", __func__); + return false; + } + + for (const FormInfo &item : targetForms) { + if (IsSameForm(record, item)) { + updatedForm = item; + APP_LOGD("%{public}s, find matched form.", __func__); + return true; + } + } + return false; +} +/** + * @brief Set isEnableUpdate for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + */ +void FormDataMgr::SetEnableUpdate(const int64_t formId, const bool enableUpdate) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.isEnableUpdate = enableUpdate; +} +/** + * @brief Set update info for FormRecord. + * @param formId The Id of the form. + * @param enableUpdate true or false. + * @param updateDuration Update duration. + * @param updateAtHour Update at hour. + * @param updateAtMin Update at minute. + */ +void FormDataMgr::SetUpdateInfo(const int64_t formId, const bool enableUpdate, const long updateDuration, +const int updateAtHour, const int updateAtMin) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + + itFormRecord->second.isEnableUpdate = enableUpdate; + itFormRecord->second.updateDuration = updateDuration; + itFormRecord->second.updateAtHour = updateAtHour; + itFormRecord->second.updateAtMin = updateAtMin; +} +/** + * @brief Check if two forms is same or not. + * @param record FormRecord. + * @param formInfo FormInfo. + * @return Returns true on success, false on failure. + */ +bool FormDataMgr::IsSameForm(const FormRecord &record, const FormInfo &formInfo) +{ + if (record.bundleName == formInfo.bundleName + && record.moduleName == formInfo.moduleName + && record.abilityName == formInfo.abilityName + && record.formName == formInfo.name + && std::find(formInfo.supportDimensions.begin(), formInfo.supportDimensions.end(), record.specification) + != formInfo.supportDimensions.end()) { + return true; + } + + return false; +} +/** + * @brief Clean removed form records. + * @param removedForms The id list of the forms. + */ +void FormDataMgr::CleanRemovedFormRecords(const std::string &bundleName, std::set &removedForms) +{ + APP_LOGI("%{public}s, clean removed form records", __func__); + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + auto itForm = std::find(removedForms.begin(), removedForms.end(), itFormRecord->first); + if (itForm != removedForms.end()) { + itFormRecord = formRecords_.erase(itFormRecord); + } + else { + itFormRecord++; + } + } +} +/** + * @brief Clean removed temp form records. + * @param bundleName BundleName. + * @param removedForms The id list of the forms. + */ +void FormDataMgr::CleanRemovedTempFormRecords(const std::string &bundleName, std::set &removedForms) +{ + APP_LOGI("%{public}s, clean removed form records", __func__); + std::set removedTempForms; + { + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { + if (itFormRecord->second.formTempFlg && bundleName == itFormRecord->second.bundleName) { + removedTempForms.emplace(itFormRecord->second.formId); + itFormRecord = formRecords_.erase(itFormRecord); + } + else { + itFormRecord++; + } + } + } + + if (removedTempForms.size() > 0) { + std::lock_guard lock(formTempMutex_); + std::vector::iterator itTemp; + for(itTemp = tempForms_.begin();itTemp != tempForms_.end();) { + if(removedTempForms.find(*itTemp) != removedTempForms.end()) { + itTemp = tempForms_.erase(itTemp); + } else { + itTemp++; + } + } + removedForms.merge(removedTempForms); + } +} +/** + * @brief Get recreate form records. + * @param reCreateForms The id list of the forms. + */ +void FormDataMgr::GetReCreateFormRecordsByBundleName(const std::string &bundleName, std::set &reCreateForms) +{ + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + if (bundleName == itFormRecord->second.bundleName) { + reCreateForms.emplace(itFormRecord->second.formId); + } + } +} +/** + * @brief Set form isInited = true. + * @param formId The Id of the form. + * @param isInited isInited property + */ +void FormDataMgr::SetFormCacheInited(const int64_t formId, bool isInited) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.isInited = isInited; + itFormRecord->second.needRefresh = !isInited; +} +/** + * @brief Set versionUpgrade. + * @param formId The Id of the form. + * @param versionUpgrade true or false + */ +void FormDataMgr::SetVersionUpgrade(const int64_t formId, const bool versionUpgrade) +{ + std::lock_guard lock(formRecordMutex_); + auto itFormRecord = formRecords_.find(formId); + if (itFormRecord == formRecords_.end()) { + APP_LOGE("%{public}s, form info not find", __func__); + return; + } + itFormRecord->second.versionUpgrade = versionUpgrade; +} +/** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param needRefresh true or false + */ +void FormDataMgr::UpdateHostNeedRefresh(const int64_t formId, const bool needRefresh) +{ + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + if (itHostRecord->Contains(formId)) { + itHostRecord->SetNeedRefresh(formId, needRefresh); + } + } +} +/** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formRecord The form info. + * @return Returns true if form update, false if other. + */ +bool FormDataMgr::UpdateHostForm(const int64_t formId, const FormRecord &formRecord) +{ + bool isUpdated = false; + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + if (itHostRecord->IsEnableRefresh(formId)) { + // update form + itHostRecord->OnUpdate(formId, formRecord); + // set needRefresh + itHostRecord->SetNeedRefresh(formId, false); + isUpdated = true; + } + } + return isUpdated; +} +/** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @param refreshForms Refresh forms + * @return Returns ERR_OK on success, others on failure. + */ +int32_t FormDataMgr::UpdateHostFormFlag(std::vector formIds, const sptr &callerToken, +const bool flag, std::vector &refreshForms) +{ + APP_LOGI("%{public}s start, flag: %{public}d", __func__, flag); + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { + if (callerToken == itHostRecord->GetClientStub()) { + for (const int64_t formId : formIds) { + if (formId <= 0) { + APP_LOGW("%{public}s, formId %{public}lld is less than 0", __func__, formId); + continue; + } + + int64_t matchedFormId = FindMatchedFormId(formId); + if (!itHostRecord->Contains(matchedFormId)) { + APP_LOGW("%{public}s, form %{public}lld is not owned by this client, don't need to update flag", + __func__, formId); + continue; + } + + itHostRecord->SetEnableRefresh(matchedFormId, flag); + // set disable + if (!flag) { + APP_LOGI("%{public}s, flag is disable", __func__); + continue; + } + FormRecord formRecord; + if (GetFormRecord(matchedFormId, formRecord)) { + if (formRecord.needRefresh) { + APP_LOGI("%{public}s, formRecord need refresh", __func__); + refreshForms.emplace_back(matchedFormId); + continue; + } + } else { + APP_LOGW("%{public}s, not exist such form:%{public}lld", __func__, matchedFormId); + continue; + } + + // if set enable flag, should check whether to refresh form + if (!itHostRecord->IsNeedRefresh(matchedFormId)) { + APP_LOGI("%{public}s, host need not refresh", __func__); + continue; + } + + if (IsFormCached(formRecord)) { + APP_LOGI("%{public}s, form cached", __func__); + itHostRecord->OnUpdate(matchedFormId, formRecord); + itHostRecord->SetNeedRefresh(matchedFormId, false); + } else { + APP_LOGI("%{public}s, form no cache", __func__); + refreshForms.emplace_back(matchedFormId); + continue; + } + } + APP_LOGI("%{public}s end.", __func__); + return ERR_OK; + } + } + APP_LOGE("%{public}s, can't find target client", __func__); + return ERR_FORM_INVALID_PARAM; +} +/** + * @brief Find matched form id. + * @param formId The form id. + * @return Matched form id. + */ +int64_t FormDataMgr::FindMatchedFormId(const int64_t formId) +{ + if ((formId & 0xffffffff00000000L) != 0) { + return formId; + } + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + if ((itFormRecord->first & 0x00000000ffffffffL) == (formId & 0x00000000ffffffffL)) { + return itFormRecord->first; + } + } + return formId; +} + +/** + * @brief Clear host data by uId. + * @param uId The caller uId. + */ +void FormDataMgr::ClearHostDataByUId(const int uId) +{ + std::lock_guard lock(formHostRecordMutex_); + std::vector::iterator itHostRecord; + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { + if (itHostRecord->GetCallerUid() == uId) { + itHostRecord->CleanResource(); + itHostRecord = clientRecords_.erase(itHostRecord); + } else { + itHostRecord++; + } + } +} +/** + * @brief Get no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ +void FormDataMgr::GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, +std::map &foundFormsMap) +{ + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + if (itFormRecord->second.formTempFlg) { + auto itUid = std::find(itFormRecord->second.formUserUids.begin(), itFormRecord->second.formUserUids.end(), + uid); + if (itUid != itFormRecord->second.formUserUids.end()) { + itFormRecord->second.formUserUids.erase(itUid); + if (itFormRecord->second.formUserUids.empty()) { + FormIdKey formIdKey; + formIdKey.bundleName = itFormRecord->second.bundleName; + formIdKey.abilityName = itFormRecord->second.abilityName; + auto itIdsSet = noHostTempFormsMap.find(formIdKey); + if (itIdsSet == noHostTempFormsMap.end()) { + std::set formIdsSet; + formIdsSet.emplace(itFormRecord->second.formId); + noHostTempFormsMap.emplace(formIdKey, formIdsSet); + } else { + itIdsSet->second.emplace(itFormRecord->second.formId); + } + } + } else { + foundFormsMap.emplace(itFormRecord->second.formId, false); + } + } + } +} +/** + * @brief Parse update config. + * @param record The form record. + * @param info The form item info. + */ +void FormDataMgr::ParseUpdateConfig(FormRecord &record, const FormItemInfo &info) const +{ + int configDuration = info.GetUpdateDuration(); + if (configDuration > 0) { + ParseIntervalConfig(record, configDuration); + } else { + ParseAtTimerConfig(record, info); + } +} + +/** + * @brief Parse update interval config. + * @param record The form record. + * @param configDuration interval duration. + */ +void FormDataMgr::ParseIntervalConfig(FormRecord &record, const int configDuration) const +{ + APP_LOGI("%{public}s, configDuration:%{public}d", __func__, configDuration); + if (configDuration <= Constants::MIN_CONFIG_DURATION) { + record.updateDuration = Constants::MIN_PERIOD; + } else if (configDuration >= Constants::MAX_CONFIG_DURATION) { + record.updateDuration = Constants::MAX_PERIOD; + } else { + record.updateDuration = configDuration * Constants::TIME_CONVERSION; + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Parse at time config. + * @param record The form record. + * @param info form item info. + */ +void FormDataMgr::ParseAtTimerConfig(FormRecord record, const FormItemInfo &info) const { + record.isEnableUpdate = false; + record.updateDuration = 0; + std::string configAtTime = info.GetScheduledUpdateTime(); + APP_LOGI("%{public}s, parseAsUpdateAt updateAt:%{public}s", __func__, configAtTime.c_str()); + if (configAtTime.empty()) { + return; + } + + std::vector temp = FormUtil::StringSplit(configAtTime, Constants::TIME_DELIMETER); + if (temp.size() != Constants::UPDATE_AT_CONFIG_COUNT) { + APP_LOGE("%{public}s, invalid config", __func__); + return; + } + int hour = -1; + int min = -1; + try { + hour = std::stoi(temp[0]); + min = std::stoi(temp[1]); + } catch (const std::exception& e) { + APP_LOGE("%{public}s, failed to stoi.", __func__); + } + + if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min > + Constants::MAX_MININUTE) { + APP_LOGE("%{public}s, time is invalid", __func__); + return; + } + record.updateAtHour = hour; + record.updateAtMin = min; + record.isEnableUpdate = true; +} +/** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ +bool FormDataMgr::IsFormCached(const FormRecord record) +{ + if (record.versionUpgrade) { + return false; + } + return FormCacheMgr::GetInstance().IsExist(record.formId); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_db_cache.cpp b/services/formmgr/src/form_db_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..74175adba1f764979bd855d619c3d9721b5c29b5 --- /dev/null +++ b/services/formmgr/src/form_db_cache.cpp @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "form_bms_helper.h" +#include "form_db_cache.h" +#include "form_db_info.h" + +namespace OHOS { +namespace AppExecFwk { +FormDbCache::FormDbCache() +{ + APP_LOGI("FormDbCache is created"); + dataStorage_ = std::make_unique(); + formDBInfos_.clear(); +} + +FormDbCache::~FormDbCache() +{ + APP_LOGI("FormDbCache is destroyed"); +} + +/** + * @brief Load form data from DB to DbCache when starting. + * @return Void. + */ +void FormDbCache::Start() +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock(formDBInfosMutex_); + std::vector innerFormInfos; + innerFormInfos.clear(); + if (dataStorage_->LoadFormData(innerFormInfos) != ERR_OK) { + APP_LOGE("%{public}s, LoadFormData failed.", __func__); + return; + } + + for (unsigned int i = 0; i < innerFormInfos.size(); i++) { + FormDBInfo formDBInfo = innerFormInfos.at(i).GetFormDBInfo(); + formDBInfos_.emplace_back(formDBInfo); + } +} + +// void FormDbCache::Stop() +// { +// APP_LOGI("stop"); +// dataStorage_->Stop(); +// } + +/** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::SaveFormInfo(const FormDBInfo &formDBInfo) +{ + APP_LOGI("%{public}s called, formId:%{public}lld", __func__, formDBInfo.formId); + std::lock_guard lock(formDBInfosMutex_); + auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), formDBInfo); + if (iter != formDBInfos_.end()) { + if (iter->Compare(formDBInfo) == false) { + APP_LOGW("%{public}s, need update, formId[%{public}lld].", __func__, formDBInfo.formId); + *iter = formDBInfo; + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->ModifyStorageFormInfo(innerFormInfo); + } else { + APP_LOGW("%{public}s, already exist, formId[%{public}lld].", __func__, formDBInfo.formId); + return ERR_OK; + } + } else { + formDBInfos_.emplace_back(formDBInfo); + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->SaveStorageFormInfo(innerFormInfo); + } +} + +/** + * @brief Save or update form data to DbCache and DB. + * @param formDBInfo Form data. + * @return Returns ERR_OK on success, others on failure.(NoLock) + */ +ErrCode FormDbCache::SaveFormInfoNolock(const FormDBInfo &formDBInfo) +{ + APP_LOGI("%{public}s called, formId:%{public}lld", __func__, formDBInfo.formId); + auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), formDBInfo); + if (iter != formDBInfos_.end()) { + if (iter->Compare(formDBInfo) == false) { + APP_LOGW("%{public}s, need update, formId[%{public}lld].", __func__, formDBInfo.formId); + *iter = formDBInfo; + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->ModifyStorageFormInfo(innerFormInfo); + } else { + APP_LOGW("%{public}s, already exist, formId[%{public}lld].", __func__, formDBInfo.formId); + return ERR_OK; + } + } else { + formDBInfos_.emplace_back(formDBInfo); + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->SaveStorageFormInfo(innerFormInfo); + } +} + +/** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::DeleteFormInfo(int64_t formId) +{ + std::lock_guard lock(formDBInfosMutex_); + FormDBInfo tmpForm; + tmpForm.formId = formId; + auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), tmpForm); + if (iter == formDBInfos_.end()) { + APP_LOGW("%{public}s, not find formId[%{public}lld]", __func__, formId); + } else { + formDBInfos_.erase(iter); + } + if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { + return ERR_OK; + } else { + return ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL; + } +} +/** + * @brief Delete form data in DbCache and DB with formId. + * @param formId form data Id. + * @param removedDBForms Removed db form infos + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::DeleteFormInfoByBundleName(const std::string &bundleName, std::vector &removedDBForms) +{ + std::lock_guard lock(formDBInfosMutex_); + std::vector::iterator itRecord; + for (itRecord = formDBInfos_.begin(); itRecord != formDBInfos_.end();) { + if (bundleName == itRecord->bundleName) { + int64_t formId = itRecord->formId; + if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { + removedDBForms.emplace_back(*itRecord); + itRecord = formDBInfos_.erase(itRecord); + } else { + itRecord++; + } + } else { + itRecord++; + } + } + return ERR_OK; +} +// bool FormDbCache::BatchDeleteForms(std::vector formIds) +// { +// std::lock_guard lock(formDBInfosMutex_); +// for (const auto& formId : formIds) { +// FormDBInfo tmpForm; +// tmpForm.formId_ = formId; +// auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), tmpForm); +// if (iter != formDBInfos_.end()) { +// formDBInfos_.erase(iter); +// } +// } +// return dataStorage_->BatchDeleteForms(formIds); +// } + +/** + * @brief Get all form data from DbCache. + * @param formDBInfos Storage all DbCache. + * @return Void. + */ +void FormDbCache::GetAllFormInfo(std::vector &formDBInfos) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock(formDBInfosMutex_); + formDBInfos = formDBInfos_; +} + +/** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormRecord &record) const +{ + std::lock_guard lock(formDBInfosMutex_); + for (const FormDBInfo &dbInfo : formDBInfos_) { + if (dbInfo.formId == formId) { + record.formName = dbInfo.formName; + record.bundleName = dbInfo.bundleName; + record.moduleName = dbInfo.moduleName; + record.abilityName = dbInfo.abilityName; + record.formUserUids = dbInfo.formUserUids; + return ERR_OK; + } + } + APP_LOGE("%{public}s, not find formId[%{public}lld]", __func__, formId); + return ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL; +} +/** + * @brief Get record from DB cache with formId + * @param formId Form data Id + * @param record Form db data + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormDBInfo &record) const +{ + std::lock_guard lock(formDBInfosMutex_); + for (const FormDBInfo &dbInfo : formDBInfos_) { + if (dbInfo.formId == formId) { + record = dbInfo; + return ERR_OK; + } + } + APP_LOGE("%{public}s, not find formId[%{public}lld]", __func__, formId); + return ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL; +} +/** + * @brief Use record save or update DB data and DB cache with formId + * @param formId Form data Id + * @param record Form data + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::UpdateDBRecord(const int64_t formId, const FormRecord &record) const +{ + FormDBInfo formDBInfo(formId, record); + return FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // FormBmsHelper::GetInstance().NotifyModuleNotRemovable(formDBInfo.bundleName, formDBInfo.moduleName); +} +/** + * @brief Get no host db record. + * @param uid The caller uid. + * @param noHostFormDBList no host db record list. + * @param foundFormsMap Form Id list. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormDbCache::GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, +std::map &foundFormsMap) +{ + std::lock_guard lock(formDBInfosMutex_); + for (FormDBInfo& dbInfo : formDBInfos_) { + if (dbInfo.Contains(uid)) { + dbInfo.Remove(uid); + if (dbInfo.formUserUids.empty()) { + FormIdKey formIdKey; + formIdKey.bundleName = dbInfo.bundleName; + formIdKey.abilityName = dbInfo.abilityName; + auto itIdsSet = noHostFormDBList.find(formIdKey); + if (itIdsSet == noHostFormDBList.end()) { + std::set formIdsSet; + formIdsSet.emplace(dbInfo.formId); + noHostFormDBList.emplace(formIdKey, formIdsSet); + } else { + itIdsSet->second.emplace(dbInfo.formId); + } + } else { + foundFormsMap.emplace(dbInfo.formId, false); + SaveFormInfoNolock(dbInfo); + FormBmsHelper::GetInstance().NotifyModuleNotRemovable(dbInfo.bundleName, dbInfo.moduleName); + } + } + } + return ERR_OK; +} +/** + * @brief Get match count by bundleName and moduleName. + * @param bundleName BundleName. + * @param moduleName ModuleName. + * @return Returns match count. + */ +int FormDbCache::GetMatchCount(const std::string &bundleName, const std::string &moduleName) +{ + int32_t matchCount {0}; + std::vector formDBInfos; + std::lock_guard lock(formDBInfosMutex_); + for (FormDBInfo &dbInfo : formDBInfos_) { + if (dbInfo.bundleName == bundleName && dbInfo.moduleName == moduleName) { + ++matchCount; + } + } + return matchCount; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_db_info.cpp b/services/formmgr/src/form_db_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4846b9bf795b361060a1411c929149d0d1a08cc0 --- /dev/null +++ b/services/formmgr/src/form_db_info.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_db_info.h" +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string FORM_ID = "formId"; +const std::string FORM_NAME = "formName"; +const std::string BUNDLE_NAME = "bundleName"; +const std::string MODULE_NAME = "moduleName"; +const std::string ABILITY_NAME = "abilityName"; +const std::string FORM_USER_UIDS = "formUserUids"; +} + +// void to_json(nlohmann::json &jsonObject, const FormDBInfo &info) +// { +// jsonObject = nlohmann::json{ +// {FORM_ID, info.formId}, +// {USER_ID, info.userId}, +// {BUNDLE_NAME, info.bundleName}, +// {MODULE_NAME, info.moduleName}, +// {ABILITY_NAME, info.abilityName}, +// {FORM_USER_UIDS, info.formUserUids} +// }; +// } + +/** + * @brief Transform the InnerFormInfo object to json. + * @param jsonObject Indicates the obtained json object. + * @return + */ +void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject[FORM_ID] = formDBInfo_.formId; + jsonObject[FORM_NAME] = formDBInfo_.formName; + jsonObject[BUNDLE_NAME] = formDBInfo_.bundleName; + jsonObject[MODULE_NAME] = formDBInfo_.moduleName; + jsonObject[ABILITY_NAME] = formDBInfo_.abilityName; + jsonObject[FORM_USER_UIDS] = formDBInfo_.formUserUids; +} + +// void from_json(const nlohmann::json &jsonObject, FormDBInfo &info) +// { +// const auto &jsonObjectEnd = jsonObject.end(); +// if (jsonObject.find(FORM_ID) != jsonObjectEnd) { +// info.formId = jsonObject.at(FORM_ID).get(); +// } + +// if (jsonObject.find(USER_ID) != jsonObjectEnd) { +// info.userId = jsonObject.at(USER_ID).get(); +// } + +// if (jsonObject.find(BUNDLE_NAME) != jsonObjectEnd) { +// info.bundleName = jsonObject.at(BUNDLE_NAME).get(); +// } + +// if (jsonObject.find(MODULE_NAME) != jsonObjectEnd) { +// info.moduleName = jsonObject.at(MODULE_NAME).get(); +// } + +// if (jsonObject.find(ABILITY_NAME) != jsonObjectEnd) { +// info.abilityName = jsonObject.at(ABILITY_NAME).get(); +// } + +// if (jsonObject.find(FORM_USER_UIDS) != jsonObjectEnd) { +// info.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); +// } +// } + +/** + * @brief Transform the json object to InnerFormInfo object. + * @param jsonObject Indicates the obtained json object. + * @return + */ +bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) +{ + // try { + formDBInfo_.formId = jsonObject.at(FORM_ID).get(); + formDBInfo_.formName = jsonObject.at(FORM_NAME).get(); + formDBInfo_.bundleName = jsonObject.at(BUNDLE_NAME).get(); + formDBInfo_.moduleName = jsonObject.at(MODULE_NAME).get(); + formDBInfo_.abilityName = jsonObject.at(ABILITY_NAME).get(); + formDBInfo_.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); + + // } catch (nlohmann::detail::parse_error &exception) { + // APP_LOGE("%{public}s, has a parse_error:%{public}s", __func__, exception.what()); + // return false; + // } catch (nlohmann::detail::type_error &exception) { + // APP_LOGE("%{public}s, has a type_error:%{public}s.", __func__, exception.what()); + // return false; + // } catch (nlohmann::detail::out_of_range &exception) { + // APP_LOGE("%{public}s, has an out_of_range exception:%{public}s.", __func__, exception.what()); + // return false; + // } catch(...) { + // APP_LOGE("%{public}s, other exception", __func__); + // return false; + // } + return true; +} + +void InnerFormInfo::AddUserUid(const int callingUid) +{ + // std::lock_guard lock(mutex_); + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + formDBInfo_.formUserUids.push_back(callingUid); + } +} + +bool InnerFormInfo::DeleteUserUid(const int callingUid) +{ + // std::lock_guard lock(mutex_); + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + return false; + } + formDBInfo_.formUserUids.erase(iter); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_delete_connection.cpp b/services/formmgr/src/form_delete_connection.cpp new file mode 100755 index 0000000000000000000000000000000000000000..098e911591a1802536d99480eb76c304727585a3 --- /dev/null +++ b/services/formmgr/src/form_delete_connection.cpp @@ -0,0 +1,56 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_delete_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormDeleteConnection::FormDeleteConnection(const int64_t formId) + :formId_(formId) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormDeleteConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}lld, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + APP_LOGD("%{public}s, connectId :%{public}ld", __func__, this->GetConnectId()); + FormTaskMgr::GetInstance().PostDeleteTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_dump_mgr.cpp b/services/formmgr/src/form_dump_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f89ca359dc4b799450e191d1f5a8a6e5648ef29 --- /dev/null +++ b/services/formmgr/src/form_dump_mgr.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_cache_mgr.h" +#include "form_dump_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string LINE_SEPARATOR = "\n"; + +FormDumpMgr::FormDumpMgr(){} +FormDumpMgr::~FormDumpMgr(){} +/** + * @brief Dump all of form storage infos. + * @param storageInfos Form storage infos + * @param formInfos Form storage dump info. + */ +void FormDumpMgr::DumpStorageFormInfos(const std::vector &storageInfos, std::string &formInfos) const +{ + for (const auto &info : storageInfos) { + formInfos += " FormId #" + std::to_string(info.formId); + formInfos += " formName [" + info.formName + "]"; + formInfos += " bundleName [" + info.bundleName + "]"; + formInfos += " moduleName [" + info.moduleName + "]"; + formInfos += " abilityName [" + info.abilityName + "]"; + formInfos += " formUserUids ["; + for (auto &uId : info.formUserUids) { + formInfos += " Uid [" + std::to_string(uId) + "]"; + } + formInfos += "]" + LINE_SEPARATOR; + } +} +/** + * @brief Dump form infos. + * @param formRecordInfos Form record infos. + * @param formInfos Form dump infos. + */ +void FormDumpMgr::DumpFormInfos(const std::vector &formRecordInfos, std::string &formInfos) const +{ + APP_LOGI("%{public}s called.", __func__); + for (const auto &info : formRecordInfos) { + formInfos += " FormId [" + std::to_string(info.formId) + "]"; + formInfos += " formName [" + info.formName + "]"; + formInfos += " bundleName [" + info.bundleName + "]"; + formInfos += " moduleName [" + info.moduleName + "]"; + formInfos += " abilityName [" + info.abilityName + "]"; + formInfos += " isInited [" + std::to_string(info.isInited) + "]"; + formInfos += " needRefresh [" + std::to_string(info.needRefresh) + "]"; + formInfos += " isEnableUpdate [" + std::to_string(info.isEnableUpdate) + "]"; + formInfos += " isCountTimerRefresh [" + std::to_string(info.isCountTimerRefresh) + "]"; + formInfos += " specification [" + std::to_string(info.specification) + "]"; + formInfos += " updateDuration [" + std::to_string(info.updateDuration) + "]"; + formInfos += " updateAtHour [" + std::to_string(info.updateAtHour) + "]"; + formInfos += " updateAtMin [" + std::to_string(info.updateAtMin) + "]"; + formInfos += " formTempFlg [" + std::to_string(info.formTempFlg) + "]"; + formInfos += " formVisibleNotify [" + std::to_string(info.formVisibleNotify) + "]"; + formInfos += " formVisibleNotifyState [" + std::to_string(info.formVisibleNotifyState) + "]"; + + if (info.hapSourceDirs.size() > 0) { + formInfos += " hapSourceDirs ["; + for (auto &hapDir : info.hapSourceDirs) { + formInfos += " hapSourceDir [" + hapDir + "]"; + } + formInfos += "]"; + } + + if (info.formUserUids.size() > 0) { + formInfos += " formUserUids ["; + for (auto &uId : info.formUserUids) { + formInfos += " Uid [" + std::to_string(uId) + "]"; + } + formInfos += "]"; + } + + // formCacheData + std::string strCacheData; + if (FormCacheMgr::GetInstance().GetData(info.formId, strCacheData)) { + formInfos += " formCacheData ["; + formInfos += strCacheData; + formInfos += "]" + LINE_SEPARATOR; + } + } + + APP_LOGI("%{public}s success. Form infos:%{public}s", __func__, formInfos.c_str()); +} +/** + * @brief Dump form infos. + * @param formRecordInfo Form Host record info. + * @param formInfo Form dump info. + */ +void FormDumpMgr::DumpFormHostInfo(const FormHostRecord &formHostRecord, std::string &formInfo) const +{ + APP_LOGI("%{public}s called.", __func__); + formInfo += " ================FormHostRecord================="; + formInfo += " callerUid [" + std::to_string(formHostRecord.GetCallerUid()) + "]"; + formInfo += " hostBundleName [" + formHostRecord.GetHostBundleName() + "]"; + APP_LOGI("%{public}s success. Host Form infos:%{public}s", __func__, formInfo.c_str()); +} + +/** + * @brief Dump form infos. + * @param formRecordInfo Form record info. + * @param formInfo Form dump info. + */ +void FormDumpMgr::DumpFormInfo(const FormRecord &formRecordInfo, std::string &formInfo) const +{ + APP_LOGI("%{public}s called.", __func__); + formInfo += " ================FormRecord================="; + formInfo += " FormId [" + std::to_string(formRecordInfo.formId) + "]"; + formInfo += " formName [" + formRecordInfo.formName + "]"; + formInfo += " bundleName [" + formRecordInfo.bundleName + "]"; + formInfo += " moduleName [" + formRecordInfo.moduleName + "]"; + formInfo += " abilityName [" + formRecordInfo.abilityName + "]"; + formInfo += " isInited [" + std::to_string(formRecordInfo.isInited) + "]"; + formInfo += " needRefresh [" + std::to_string(formRecordInfo.needRefresh) + "]"; + formInfo += " isEnableUpdate [" + std::to_string(formRecordInfo.isEnableUpdate) + "]"; + formInfo += " isCountTimerRefresh [" + std::to_string(formRecordInfo.isCountTimerRefresh) + "]"; + formInfo += " specification [" + std::to_string(formRecordInfo.specification) + "]"; + formInfo += " updateDuration [" + std::to_string(formRecordInfo.updateDuration) + "]"; + formInfo += " updateAtHour [" + std::to_string(formRecordInfo.updateAtHour) + "]"; + formInfo += " updateAtMin [" + std::to_string(formRecordInfo.updateAtMin) + "]"; + formInfo += " formTempFlg [" + std::to_string(formRecordInfo.formTempFlg) + "]"; + formInfo += " formVisibleNotify [" + std::to_string(formRecordInfo.formVisibleNotify) + "]"; + formInfo += " formVisibleNotifyState [" + std::to_string(formRecordInfo.formVisibleNotifyState) + "]"; + + if (formRecordInfo.hapSourceDirs.size() > 0) { + formInfo += " hapSourceDirs ["; + for (auto &hapDir : formRecordInfo.hapSourceDirs) { + formInfo += " hapSourceDir [" + hapDir + "]"; + } + formInfo += "]"; + } + + if (formRecordInfo.formUserUids.size() > 0) { + formInfo += " formUserUids ["; + for (auto &uId : formRecordInfo.formUserUids) { + formInfo +=" Uid [" + std::to_string(uId) + "]"; + } + formInfo += "]"; + } + + // formCacheData + std::string strCacheData; + if (FormCacheMgr::GetInstance().GetData(formRecordInfo.formId, strCacheData)) { + formInfo += " formCacheData ["; + formInfo += strCacheData; + formInfo += "]" + LINE_SEPARATOR; + } + + APP_LOGI("%{public}s success. Form infos:%{public}s", __func__, formInfo.c_str()); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_event_notify_connection.cpp b/services/formmgr/src/form_event_notify_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cea26ab8e3ff06a79d7343523a70ae7476862f77 --- /dev/null +++ b/services/formmgr/src/form_event_notify_connection.cpp @@ -0,0 +1,60 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_event_notify_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormEventNotifyConnection::FormEventNotifyConnection(const std::vector formEvents, +const int32_t formVisibleType) + :formEvents_(formEvents), + formVisibleType_(formVisibleType) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormEventNotifyConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostEventNotifyTask(formEvents_, formVisibleType_, want, remoteObject); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_host_callback.cpp b/services/formmgr/src/form_host_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41dab8f27de32c92adfc4a6d62dd9a8494b15ef7 --- /dev/null +++ b/services/formmgr/src/form_host_callback.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_host_callback.h" +#include "form_host_interface.h" +#include "form_task_mgr.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Request to give back a Form. + * @param formId The Id of the forms to create. + * @param record Form record. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +void FormHostCallback::OnAcquired(const int64_t formId, const FormRecord& record, +const sptr &callerToken) +{ + APP_LOGD("FormHostCallback OnAcquired, formId:%{public}lld", formId); + FormTaskMgr::GetInstance().PostAcquireTaskToHost(formId, record, callerToken); +} + + +/** +* @brief Form is updated. +* @param formId The Id of the form to update. +* @param record Form record. +* @param callerToken Caller ability token. +* @return Returns ERR_OK on success, others on failure. +*/ +void FormHostCallback::OnUpdate(const int64_t formId, const FormRecord &record, const sptr &callerToken) +{ + APP_LOGI("%{public}s start.", __func__); + + // check formId + if (formId < 0) { + APP_LOGE("%{public}s: OnUpdate invalid param, formId:%{public}lld.", __func__, formId); + return; + } + + if (callerToken == nullptr) { + APP_LOGE("%{public}s: callerToken can not be NULL", __func__); + return; + } + + // post updateTask to host + FormTaskMgr::GetInstance().PostUpdateTaskToHost(formId, record, callerToken); +} + +/** + * @brief Form provider is uninstalled + * @param formIds The Id list of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +void FormHostCallback::OnUninstall(std::vector &formIds, const sptr &callerToken) +{ + // check formId + if (formIds.size() <= 0) { + APP_LOGE("%{public}s: OnUninstall invalid param, formIds is empty.", __func__); + return; + } + + if (callerToken == nullptr) { + APP_LOGE("%{public}s: callerToken can not be NULL", __func__); + return; + } + // post updateTask to host + FormTaskMgr::GetInstance().PostUninstallTaskToHost(formIds, callerToken); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_host_record.cpp b/services/formmgr/src/form_host_record.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b276a1c8b7bface38ece447b3a13c09c3f949ec --- /dev/null +++ b/services/formmgr/src/form_host_record.cpp @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2021 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 "form_host_record.h" +#include "form_task_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Add form id. + * @param formId The Id of the form. + */ +void FormHostRecord::AddForm(int64_t formId) +{ + if (forms_.find(formId) != forms_.end()) { + return; + } + forms_[formId] = true; +} +/** + * @brief Delete form id. + * @param formId The Id of the form. + */ +void FormHostRecord::DelForm(int64_t formId) +{ + forms_.erase(formId); +} +/** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ +bool FormHostRecord::IsEmpty() const +{ + return forms_.empty(); +} +/** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ +bool FormHostRecord::Contains(int64_t formId) const +{ + return forms_.find(formId) != forms_.end(); +} + +/** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetEnableRefresh(int64_t formId, bool flag) +{ + if (forms_.find(formId) == forms_.end()) { + return; + } + forms_[formId] = flag; +} +/** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsEnableRefresh(int64_t formId) const +{ + auto result = forms_.find(formId); + if (result != forms_.end()) { + return result->second; + } + return false; +} +/** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetNeedRefresh(int64_t formId, bool flag) +{ + needRefresh_[formId] = flag; +} +/** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsNeedRefresh(int64_t formId) const +{ + auto result = needRefresh_.find(formId); + if (result != needRefresh_.end()) { + return result->second; + } + return false; +} +/** + * @brief Get clientStub_. + * @return clientStub_. + */ +sptr FormHostRecord::GetClientStub() const +{ + return clientStub_; +} + +/** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnAcquire(int64_t id, const FormRecord &record) +{ + APP_LOGD("FormHostRecord OnAcquire"); + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be NULL", __func__); + return; + } + + clientImpl_->OnAcquired(id, record, clientStub_); +} + +/** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnUpdate(int64_t id, const FormRecord &record) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + + clientImpl_->OnUpdate(id, record, clientStub_); +} + +/** + * @brief Send form uninstall message to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnFormUninstalled(std::vector &formIds) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + clientImpl_->OnUninstall(formIds, clientStub_); +} +/** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::CleanResource() +{ + if (clientStub_ != nullptr && deathRecipient_ != nullptr) { + clientStub_->RemoveDeathRecipient(deathRecipient_); + clientStub_ = nullptr; + deathRecipient_ = nullptr; + } +} +/** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ +void FormHostRecord::SetCallerUid(const int callerUid) +{ + callerUid_ = callerUid; +} +/** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ +void FormHostRecord::SetClientStub(const sptr &clientStub) +{ + clientStub_ = clientStub; +} +/** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ +void FormHostRecord::SetClientImpl(const std::shared_ptr &clientImpl) +{ + clientImpl_ = clientImpl; +} +/** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ +sptr FormHostRecord::GetDeathRecipient() const +{ + return deathRecipient_; +} +/** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ +void FormHostRecord::SetDeathRecipient(const sptr &deathRecipient) +{ + deathRecipient_ = deathRecipient; +} +/** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ +void FormHostRecord::AddDeathRecipient(const sptr &deathRecipient) +{ + clientStub_->AddDeathRecipient(deathRecipient); +} + +/** + * @brief Create form host record. + * @param info The form item info. + * @param callback remote object. + * @param callingUid Calling uid. + */ +FormHostRecord FormHostRecord::CreateRecord(const FormItemInfo &info, const sptr &callback, +int callingUid) +{ + FormHostRecord record; + record.SetHostBundleName(info.GetHostBundleName()); + record.SetCallerUid(callingUid); + record.SetClientStub(callback); + record.SetClientImpl(std::make_shared()); + record.SetDeathRecipient(new FormHostRecord::ClientDeathRecipient()); + record.AddDeathRecipient(record.GetDeathRecipient()); + + return record; +} + +/** + * @brief handle remote object died event. + * @param remote remote object. + */ +void FormHostRecord::ClientDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGD("Form remote died"); + FormTaskMgr::GetInstance().PostHostDiedTask(remote.promote()); +} + +/** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ +std::string FormHostRecord::GetHostBundleName() const +{ + return hostBundleName_; +} +/** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ +void FormHostRecord::SetHostBundleName(const std::string &hostBundleName) +{ + hostBundleName_ = hostBundleName; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_item_info.cpp b/services/formmgr/src/form_item_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b686c4f61dabfd5f4f5c9041c1e976499fd5e587 --- /dev/null +++ b/services/formmgr/src/form_item_info.cpp @@ -0,0 +1,370 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_item_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Get formId_. + * @return formId_. + */ +int64_t FormItemInfo::GetFormId() const +{ + return formId_; +} +/** + * @brief Get packageName_. + * @return packageName_. + */ +std::string FormItemInfo::GetPackageName() const +{ + return packageName_; +} +/** + * @brief Get providerBundleName_. + * @return providerBundleName_. + */ +std::string FormItemInfo::GetProviderBundleName() const +{ + return providerBundleName_; +} +/** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ +std::string FormItemInfo::GetHostBundleName() const +{ + return hostBundleName_; +} +/** + * @brief Get moduleName_. + * @return moduleName_. + */ +std::string FormItemInfo::GetModuleName() const +{ + return moduleName_; +} +/** + * @brief Get abilityName_. + * @return abilityName_. + */ +std::string FormItemInfo::GetAbilityName() const +{ + return abilityName_; +} +/** + * @brief Get formName_. + * @return formName_. + */ +std::string FormItemInfo::GetFormName() const +{ + return formName_; +} +/** + * @brief Get jsComponentName_. + * @return jsComponentName_. + */ +std::string FormItemInfo::GetJsComponentName() const +{ + return jsComponentName_; +} +/** + * @brief Get abilityModuleName_. + * @return abilityModuleName_. + */ +std::string FormItemInfo::GetAbilityModuleName() const +{ + return abilityModuleName_; +} +/** + * @brief Get specificationId_. + * @return specificationId_. + */ +int FormItemInfo::GetSpecificationId() const +{ + return specificationId_; +} + +/** + * @brief Obtains the updageFlag. + * @return Returns updageFlag. + */ +bool FormItemInfo::IsEnableUpdateFlag() const +{ + return updateFlag_; +} +/** + * @brief Get updateDuration_. + * @return updateDuration_. + */ +int FormItemInfo::GetUpdateDuration() const +{ + return updateDuration_; +} +/** + * @brief Get scheduledUpdateTime_. + * @return scheduledUpdateTime_. + */ +std::string FormItemInfo::GetScheduledUpdateTime() const +{ + return scheduledUpdateTime_; +} + +/** + * @brief Get hapSourceDirs_. + * @param dirs Hap source dirs. + * @return Returns true on success, false on failure. + */ +bool FormItemInfo::GetHapSourceDirs(std::vector &dirs) const +{ + if (hapSourceDirs_.size() > 0) { + dirs.assign(hapSourceDirs_.begin(), hapSourceDirs_.end()); + return true; + } + return false; +} +/** + * @brief Set value of hapSourceDirs_. + * @param hapSourceDirs Hap source dirs. + */ +void FormItemInfo::SetHapSourceDirs(const std::vector &hapSourceDirs) +{ + hapSourceDirs_ = hapSourceDirs; +} +/** + * @brief Obtains the temporaryFlag. + * @return Returns temporaryFlag. + */ +bool FormItemInfo::IsTemporaryForm() const +{ + return temporaryFlag_; +} + +/** + * @brief Obtains the hap source by ability module name. + * @param moduleName ability module name + * @return Returns hap source. + */ +std::string FormItemInfo::GetHapSourceByModuleName(const std::string &moduleName) const +{ + auto iter = moduleInfoMap_.find(moduleName); + if (iter != moduleInfoMap_.end()) { + return iter->second; + } + return ""; +} +/** + * @brief Check if item valid or not. + * @return Valid or not + */ +bool FormItemInfo::IsValidItem() const +{ + if (providerBundleName_.empty() || moduleName_.empty() + || abilityName_.empty() || formName_.empty()) { + return false; + } + return true; +} +/** + * @brief Check if item match or not. + * @return Match or not + */ +bool FormItemInfo::IsMatch(const FormRecord &record) const +{ + APP_LOGD("match data"); + APP_LOGD("FormRecord.bundleName : %{public}s", record.bundleName.c_str()); + APP_LOGD("FormRecord.moduleName : %{public}s", record.moduleName.c_str()); + APP_LOGD("FormRecord.abilityName : %{public}s", record.abilityName.c_str()); + APP_LOGD("FormRecord.formName : %{public}s", record.formName.c_str()); + APP_LOGD("FormRecord.specification : %{public}d", record.specification); + + APP_LOGD("FormItemInfo.providerBundleName_ : %{public}s", providerBundleName_.c_str()); + APP_LOGD("FormItemInfo.moduleName : %{public}s", moduleName_.c_str()); + APP_LOGD("FormItemInfo.abilityName : %{public}s", abilityName_.c_str()); + APP_LOGD("FormItemInfo.formName : %{public}s", formName_.c_str()); + APP_LOGD("FormItemInfo.specification : %{public}d", specificationId_); + + return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) + && (record.abilityName == abilityName_) && (record.formName == formName_) + && (record.specification == specificationId_); +} +/** + * @brief Check if form config same or not. + * @return Same or not + */ +bool FormItemInfo::IsSameFormConfig(const FormRecord &record) const +{ + return (record.bundleName == providerBundleName_) && (record.moduleName == moduleName_) + && (record.abilityName == abilityName_) && (record.formName == formName_); +} + +/** + * @brief Check if visible notify or not. + * @return visible notify or not + */ +bool FormItemInfo::IsFormVisibleNotify() const +{ + return formVisibleNotify_; +} +/** + * @brief Equal or not. + * @param left left string. + * @param right right string. + * @return Equal or not + */ +bool FormItemInfo::IsEqual(const std::string &left, const std::string &right) +{ + return left == right; +} +/** + * @brief Set value of formId_. + * @param formId Form Id. + */ +void FormItemInfo::SetFormId(int64_t formId) +{ + formId_ = formId; +} +/** + * @brief Set value of packageName_. + * @param packageName Package name. + */ +void FormItemInfo::SetPackageName(const std::string &packageName) +{ + packageName_ = packageName; +} +/** + * @brief Set value of providerBundleName_. + * @param providerBundleName Provider bundle Name. + */ +void FormItemInfo::SetProviderBundleName(const std::string &providerBundleName) +{ + providerBundleName_ = providerBundleName; +} +/** + * @brief Set value of hostBundleName_. + * @param hostBundleName Host bundle Name. + */ +void FormItemInfo::SetHostBundleName(const std::string &hostBundleName) +{ + hostBundleName_ = hostBundleName; +} +/** + * @brief Set value of moduleName_. + * @param moduleName Module Name. + */ +void FormItemInfo::SetModuleName(const std::string &moduleName) +{ + moduleName_ = moduleName; +} +/** + * @brief Set value of abilityName_. + * @param abilityName Ability name. + */ +void FormItemInfo::SetAbilityName(const std::string &abilityName) +{ + abilityName_ = abilityName; +} +/** + * @brief Set value of formName_. + * @param formName Form name. + */ +void FormItemInfo::SetFormName(const std::string &formName) +{ + formName_ = formName; +} +/** + * @brief Set value of jsComponentName_. + * @param jsComponentName Js component name. + */ +void FormItemInfo::SetJsComponentName(const std::string &jsComponentName) +{ + jsComponentName_ = jsComponentName; +} +/** + * @brief Set value of abilityModuleName_. + * @param abilityModuleName ability module name_. + */ +void FormItemInfo::SetAbilityModuleName(const std::string &abilityModuleName) +{ + abilityModuleName_ = abilityModuleName; +} +/** + * @brief Set value of specificationId_. + * @param specificationId Specification id. + */ +void FormItemInfo::SetSpecificationId(const int specificationId) +{ + specificationId_ = specificationId; +} +/** + * @brief Set value of updateFlag_. + * @param IsEnableUpdateFlag Enable update flag or not. + */ +void FormItemInfo::SetEnableUpdateFlag(bool IsEnableUpdateFlag) +{ + updateFlag_ = IsEnableUpdateFlag; +} +/** + * @brief Set value of updateDuration_. + * @param updateDuration Update duration. + */ +void FormItemInfo::SetUpdateDuration(int updateDuration) +{ + updateDuration_ = updateDuration; +} +/** + * @brief Set value of scheduledUpdateTime_. + * @param scheduledUpdateTime Scheduled update time. + */ +void FormItemInfo::SetScheduledUpdateTime(const std::string &scheduledUpdateTime) +{ + scheduledUpdateTime_ = scheduledUpdateTime; +} +/** + * @brief Add hap source dir. + * @param hapSourceDir Hap source dir. + */ +void FormItemInfo::AddHapSourceDirs(const std::string &hapSourceDir) +{ + hapSourceDirs_.emplace_back(hapSourceDir); +} +/** + * @brief Set value of temporaryFlag_. + * @param temporaryFlag Temporary flag. + */ +void FormItemInfo::SetTemporaryFlag(bool temporaryFlag) +{ + temporaryFlag_ = temporaryFlag; +} +/** + * @brief Add module info. + * @param moduleName Module name. + * @param moduleSourceDir Module source dir. + */ +void FormItemInfo::AddModuleInfo(const std::string &moduleName, const std::string &moduleSourceDir) +{ + moduleInfoMap_.emplace(std::make_pair(moduleName, moduleSourceDir)); +} +/** + * @brief Set value of formVisibleNotify_. + * @param isFormVisibleNotify visible notify or not. + */ +void FormItemInfo::SetFormVisibleNotify(bool isFormVisibleNotify) +{ + formVisibleNotify_ = isFormVisibleNotify; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dbf738eca6ced78a3f63eb5bdff2408e1024dcd2 --- /dev/null +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -0,0 +1,1399 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_acquire_connection.h" +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_cache_mgr.h" +#include "form_cast_temp_connection.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_delete_connection.h" +#include "form_db_cache.h" +#include "form_db_info.h" +#include "form_dump_mgr.h" +#include "form_event_notify_connection.h" +#include "form_mgr_adapter.h" +#include "form_provider_info.h" +#include "form_provider_mgr.h" +#include "form_refresh_connection.h" +#include "form_timer_mgr.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "ohos_account_kits.h" +#include "power_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +// /** +// * @brief Get moduleName from packageName and abilityName. +// * @param packageName Package name. +// * @param abilityName Ability name. +// * @return ModuleName. +// */ +// std::string GetFullClassName(const std::string& packageName, const std::string& abilityName) +// { +// std::string fullName; +// if (!abilityName.empty() && abilityName[0] == '.') { +// fullName = packageName + abilityName; +// } else { +// fullName = abilityName; +// } +// return fullName; +// } + +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) +{ + if (formId < 0 || callerToken == nullptr) { + APP_LOGE("%{public}s fail, callerToken can not be NULL", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + // check form count limit + bool tempFormFlag = want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + int callingUid = IPCSkeleton::GetCallingUid(); + int checkCode; + if (tempFormFlag) { + if (formId > 0) { + APP_LOGE("%{public}s fail, temp form id is invalid, formId:%{public}lld", __func__, formId); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + checkCode = FormDataMgr::GetInstance().CheckTempEnoughForm(); + } else { + checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid); + } + if (checkCode != 0) { + APP_LOGE("%{public}s fail, too much forms in system", __func__); + return checkCode; + } + + // get from comfig info + FormItemInfo formItemInfo; + int32_t errCode = GetFormConfigInfo(want, formItemInfo); + formItemInfo.SetFormId(formId); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s fail, get form config info failed.", __func__); + return errCode; + } + if (!formItemInfo.IsValidItem()) { + APP_LOGE("%{public}s fail, input param itemInfo is invalid", __func__); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + if (!FormDataMgr::GetInstance().GenerateUdidHash()) { + APP_LOGE("%{public}s fail, generate udid hash failed", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + WantParams wantParams = want.GetParams(); + if (formId > 0) { + return AllotFormById(formItemInfo, callerToken, wantParams, formInfo); + } else { + return AllotFormByInfo(formItemInfo, callerToken, wantParams, formInfo); + } +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + if (formId <= 0 || callerToken == nullptr) { + APP_LOGE("%{public}s, deleteForm invalid param", __func__); + return ERR_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { + // delete temp form if receive delete form call + return HandleDeleteTempForm(matchedFormId, callerToken); + } + return HandleDeleteForm(matchedFormId, callerToken); +} + +/** + * @brief Release forms with formIds, send formIds to form Mgr service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + APP_LOGI("%{public}s called.", __func__); + + if (formId <= 0 || callerToken == nullptr) { + APP_LOGE("%{public}s, releaseForm invalid param", __func__); + return ERR_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { + // delete temp form if receive release form call + return HandleDeleteTempForm(matchedFormId, callerToken); + } + + if (delCache) { + if (ErrCode result = HandleReleaseForm(matchedFormId, callerToken); result != ERR_OK) { + APP_LOGE("%{public}s, release form error.", __func__); + return result; + } + } + + if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, matchedFormId)) { + APP_LOGE("%{public}s, failed to remove host record", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if (!FormTimerMgr::GetInstance().RemoveFormTimer(matchedFormId)) { + APP_LOGE("%{public}s, remove timer error", __func__); + return ERR_DELETE_FORM_TIMER; + } + return ERR_OK; +} + +/** + * @brief Handle release form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleReleaseForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + if (!FormDataMgr::GetInstance().ExistFormRecord(formId)) { + APP_LOGE("%{public}s, not exist such db or temp form:%{public}lld", __func__, formId); + return ERR_NOT_EXIST_ID; + } + + FormHostRecord hostRecord; + bool hasHostRec = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, hostRecord); + bool isSelfId = hasHostRec && hostRecord.Contains(formId); + if (!isSelfId) { + APP_LOGE("%{public}s, not self form:%{public}lld", __func__, formId); + return ERR_OPERATION_FORM_NOT_SELF; + } + + APP_LOGD("%{public}s, release formRecords, formId: %{public}lld", __func__, formId); + FormDataMgr::GetInstance().DeleteFormUserUid(formId, IPCSkeleton::GetCallingUid()); + if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) { + FormDataMgr::GetInstance().DeleteFormRecord(formId); + if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) { + APP_LOGE("%{public}s, remove timer error", __func__); + return ERR_DELETE_FORM_TIMER; + } + } + return ERR_OK; +} + +/** + * @brief Handle delete form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleDeleteForm(const int64_t formId, const sptr &callerToken) +{ + FormRecord dbRecord; + if (FormDbCache::GetInstance().GetDBRecord(formId, dbRecord) != ERR_OK) { + APP_LOGE("%{public}s, not exist such db or temp form:%{public}lld", __func__, formId); + return ERR_NOT_EXIST_ID; + } + + int callingUid = IPCSkeleton::GetCallingUid(); + bool isSelfDbFormId = (std::find(dbRecord.formUserUids.begin(), dbRecord.formUserUids.end(), callingUid) != + dbRecord.formUserUids.end()) ? true : false; + + if (!isSelfDbFormId) { + APP_LOGE("%{public}s, not self form:%{public}lld", __func__, formId); + return ERR_OPERATION_FORM_NOT_SELF; + } + + if (ErrCode result = HandleDeleteFormCache(dbRecord, callingUid, formId); result != ERR_OK) { + return result; + } + + if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) { + APP_LOGE("%{public}s, failed to remove host record", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + return ERR_OK; +} + +/** + * @brief Handle delete temp form. + * @param formId The form id. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleDeleteTempForm(const int64_t formId, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + int uid = IPCSkeleton::GetCallingUid(); + FormRecord record; + bool isFormRecExist = FormDataMgr::GetInstance().GetFormRecord(formId, record); + bool isSelfTempFormId = false; + if (isFormRecExist && record.formTempFlg) { + isSelfTempFormId = (std::find(record.formUserUids.begin(), record.formUserUids.end(), uid) != + record.formUserUids.end()) ? true : false; + } + if (!isSelfTempFormId) { + APP_LOGE("%{public}s, not self form:%{public}lld", __func__, formId); + return ERR_OPERATION_FORM_NOT_SELF; + } + + FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid); + if (!FormDataMgr::GetInstance().HasFormUserUids(formId)) { + int result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, record); + if (result != ERR_OK) { + APP_LOGE("%{public}s, failed!", __func__); + FormDataMgr::GetInstance().AddFormUserUid(formId, uid); + return result; + } + FormDataMgr::GetInstance().DeleteTempForm(formId); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + if (!FormCacheMgr::GetInstance().DeleteData(formId)) { + APP_LOGE("%{public}s, failed to remove cache data", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + + if (!FormDataMgr::GetInstance().DeleteHostRecord(callerToken, formId)) { + APP_LOGE("%{public}s, failed to remove host record", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + APP_LOGD("%{public}s, record.formUserUids size: %{public}d", __func__, record.formUserUids.size()); + return ERR_OK; +} + +/** + * @brief Handle delete form cache. + * @param dbRecord Form storage information. + * @param uid calling user id. + * @param formId The form id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleDeleteFormCache(FormRecord &dbRecord, const int uid, const int64_t formId) +{ + APP_LOGD("%{public}s, delete formDBRecords, formId: %{public}lld", __func__, formId); + auto iter = std::find(dbRecord.formUserUids.begin(), dbRecord.formUserUids.end(), uid); + if (iter != dbRecord.formUserUids.end()) { + dbRecord.formUserUids.erase(iter); + } + + ErrCode result = ERR_OK; + if (dbRecord.formUserUids.empty()) { + result = FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, dbRecord); + if (result != ERR_OK) { + APP_LOGE("%{public}s, failed to notify provider form delete", __func__); + return result; + } + if (!FormDataMgr::GetInstance().DeleteFormRecord(formId)) { + APP_LOGE("%{public}s, failed to remove cache data", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if (result = FormDbCache::GetInstance().DeleteFormInfo(formId); result != ERR_OK) { + APP_LOGE("%{public}s, failed to remove db data", __func__); + return result; + } + + int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(dbRecord.bundleName, dbRecord.moduleName); + if (matchCount == 0) { + FormBmsHelper::GetInstance().NotifyModuleRemovable(dbRecord.bundleName, dbRecord.moduleName); + } + + if (!FormCacheMgr::GetInstance().DeleteData(formId)) { + APP_LOGE("%{public}s, failed to remove cache data", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + if (!FormTimerMgr::GetInstance().RemoveFormTimer(formId)) { + APP_LOGE("%{public}s, remove timer error", __func__); + return ERR_DELETE_FORM_TIMER; + } + return ERR_OK; + } + + if (result = FormDbCache::GetInstance().UpdateDBRecord(formId, dbRecord); result != ERR_OK) { + return result; + } + + APP_LOGD("%{public}s, dbRecord.formUserUids size: %{public}d", __func__, dbRecord.formUserUids.size()); + FormBmsHelper::GetInstance().NotifyModuleNotRemovable(dbRecord.bundleName, dbRecord.moduleName); + if (!FormDataMgr::GetInstance().DeleteFormUserUid(formId, uid)) { + APP_LOGE("%{public}s, failed to remove form user uid", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + return result; +} + + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formProviderData form provider data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::UpdateForm(const int64_t formId, const std::string &bundleName, +const FormProviderData &formProviderData) +{ + APP_LOGI("%{public}s start.", __func__); + + // check formId and bundleName + if (formId <= 0 || bundleName.empty()) { + APP_LOGE("%{public}s error, the passed in formId can't be negative or zero, bundleName is not empty.", + __func__); + return ERR_FORM_INVALID_PARAM; + } + + // get IBundleMgr + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + // check bundle uid for permission + int32_t userId {0}; + int32_t callingUid = IPCSkeleton::GetCallingUid(); + int32_t bundleUid = iBundleMgr->GetUidByBundleName(bundleName, userId); + if (bundleUid != callingUid) { + APP_LOGE("%{public}s error, permission denied, the updated form is not your own.", __func__); + return ERR_FORM_INVALID_PARAM; + } + + // find matched formId + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + + // check exist and get the formRecord + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGE("%{public}s error, not exist such form:%{public}lld.", __func__, matchedFormId); + return ERR_NOT_EXIST_ID; + } + + // check then form under current user + if (!FormDataMgr::GetInstance().IsCallingUidValid(formRecord.formUserUids)) { + APP_LOGE("%{public}s error, not under current user, formId:%{public}lld.", __func__, matchedFormId); + return ERR_NOT_EXIST_ID; + } + + // check bundleName match + if (formRecord.bundleName.compare(bundleName) != 0) { + APP_LOGE("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str()); + return ERR_FORM_INVALID_PARAM; + } + + // update Form + return FormProviderMgr::GetInstance().UpdateForm(matchedFormId, formRecord, formProviderData); +} + +/** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + if (callerToken == nullptr) { + APP_LOGE("%{public}s fail, callerToken can not be NULL.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + + if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId)) { + APP_LOGE("%{public}s fail, not exist such formId:%{public}lld.", __func__, matchedFormId); + return ERR_NOT_EXIST_ID; + } + + FormHostRecord formHostRecord; + bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); + if (!isHostExist) { + APP_LOGE("%{public}s fail, cannot find target client.", __func__); + return ERR_FORM_INVALID_PARAM; + } + + if (!formHostRecord.Contains(matchedFormId)) { + APP_LOGE("%{public}s fail, form is not self-owned.", __func__); + return ERR_OPERATION_FORM_NOT_SELF; + } + + APP_LOGI("%{public}s, find target client.", __func__); + return FormProviderMgr::GetInstance().RefreshForm(matchedFormId, want); +} + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * + * @param formIds The vector of form Ids. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector &formIds, +const sptr &callerToken, + const int32_t formVisibleType) +{ + APP_LOGI("%{public}s called.", __func__); + + if (callerToken == nullptr) { + APP_LOGE("%{public}s fail, callerToken can not be NULL.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s fail, failed to get IBundleMgr.", __func__); + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + int64_t matchedFormId; + std::map> eventMaps; + for (int64_t formId : formIds) { + if (formId <= 0) { + APP_LOGW("%{public}s, formId %{public}lld is less than 0", __func__, formId); + continue; + } + matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGW("%{public}s fail, not exist such form, formId:%{public}lld.", __func__, matchedFormId); + continue; + } + + FormHostRecord formHostRecord; + bool hasFormHostRecord = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); + if (!(hasFormHostRecord && formHostRecord.Contains(matchedFormId))) { + APP_LOGW("%{public}s fail, form is not belong to self, formId:%{public}lld.", __func__, matchedFormId); + continue; + } + + formRecord.formVisibleNotifyState = formVisibleType; + if (!FormDataMgr::GetInstance().UpdateFormRecord(matchedFormId, formRecord)) { + APP_LOGW("%{public}s fail, set formVisibleNotifyState error, formId:%{public}lld.", + __func__, matchedFormId); + continue; + } + + // If the form need refrsh flag is true and form visibleType is FORM_VISIBLE, refresh the form host. + if (formRecord.needRefresh && formVisibleType == Constants::FORM_VISIBLE) { + std::string cacheData; + // If the form has business cache, refresh the form host. + if (FormCacheMgr::GetInstance().GetData(matchedFormId, cacheData)) { + formRecord.formProviderInfo.SetFormDataString(cacheData); + formHostRecord.OnUpdate(matchedFormId, formRecord); + } + } + + // If the form provider is system app and the config item 'formVisibleNotify' is true, + // notify the form provider that the current form is visible. + BundleInfo bundleInfo; + if (iBundleMgr->GetBundleInfo(formRecord.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo)) { + APP_LOGD("%{public}s, get bundle uid success", __func__); + if (!iBundleMgr->CheckIsSystemAppByUid(bundleInfo.uid)) { + APP_LOGW("%{public}s fail, form provider is not system app, formId:%{public}lld.", __func__, matchedFormId); + continue; + } + } else { + APP_LOGW("%{public}s fail, can not get bundleInfo's uid", __func__); + continue; + } + if (!formRecord.formVisibleNotify) { + APP_LOGW("%{public}s fail, the config item 'formVisibleNotify' is false, formId:%{public}lld.", + __func__, matchedFormId); + continue; + } + + std::string providerKey = formRecord.bundleName + Constants::NAME_DELIMITER + formRecord.abilityName; + auto iter = eventMaps.find(providerKey); + if (iter == eventMaps.end()) { + std::vector formEventsByProvider {matchedFormId}; + eventMaps.insert(std::make_pair(providerKey, formEventsByProvider)); + } else { + iter->second.emplace_back(matchedFormId); + } + } + + for (auto iter = eventMaps.begin(); iter != eventMaps.end(); iter++) { + if (HandleEventNotify(iter->first, iter->second, formVisibleType) != ERR_OK) { + APP_LOGW("%{public}s fail, HandleEventNotify error, key is %{public}s.", __func__, iter->first.c_str()); + } + } + + return ERR_OK; +} + +/** + * @brief Temp form to normal form. + * @param formId The Id of the form. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + if (formId <= 0 || callerToken == nullptr) { + APP_LOGE("%{public}s, invalid param", __func__); + return ERR_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) || + !FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { + APP_LOGE("%{public}s, not exist such temp form:%{public}lld", __func__, matchedFormId); + return ERR_NOT_EXIST_ID; + } + + FormHostRecord record; + bool hasHostRec = FormDataMgr::GetInstance().GetFormHostRecord(matchedFormId, record); + if (!hasHostRec || !record.Contains(matchedFormId)) { + APP_LOGE("%{public}s, not self form:%{public}lld", __func__, matchedFormId); + return ERR_OPERATION_FORM_NOT_SELF; + } + + int callingUid = IPCSkeleton::GetCallingUid(); + int checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid); + if (checkCode != 0) { + APP_LOGE("%{public}s, %{public}lld failed,because if too mush forms", __func__, matchedFormId); + return checkCode; + } + + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGE("%{public}s fail, not exist such form:%{public}lld.", __func__, matchedFormId); + return ERR_NOT_EXIST_ID; + } + int bindSupplierCheckCode = HandleCastTempForm(matchedFormId, formRecord); + if (bindSupplierCheckCode != 0) { + APP_LOGE("%{public}s, cast temp form bindSupplier failed", __func__); + return bindSupplierCheckCode; + } + + if (!FormDataMgr::GetInstance().DeleteTempForm(matchedFormId)) { + APP_LOGE("%{public}s fail, delete temp form error, formId:%{public}lld.", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + if (!FormDataMgr::GetInstance().ModifyFormTempFlg(matchedFormId, false)) { + APP_LOGE("%{public}s fail, modify form temp flag error, formId:%{public}lld.", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + if (!FormDataMgr::GetInstance().AddFormUserUid(matchedFormId, callingUid)) { + APP_LOGE("%{public}s fail, add form user uid error, formId:%{public}lld.", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + if (std::find(formRecord.formUserUids.begin(), formRecord.formUserUids.end(), + callingUid) == formRecord.formUserUids.end()) { + formRecord.formUserUids.emplace_back(callingUid); + } + if (ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(matchedFormId, formRecord); errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, update db record error, formId:%{public}lld.", __func__, matchedFormId); + return errorCode; + } + + // start timer + return AddFormTimer(formRecord); +} +/** + * @brief Handle cast temp form. + * @param formId The form id. + * @param record Form information. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleCastTempForm(const int64_t formId, const FormRecord &record) +{ + APP_LOGD("%{public}s, cast temp form to normal form, notify supplier, package:%{public}s, class:%{public}s", + __func__, record.bundleName.c_str(), record.abilityName.c_str()); + sptr castTempConnection = new FormCastTempConnection(formId); + + Want want; + want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + want.SetElementName(record.bundleName, record.abilityName); + return FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection); +} +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const +{ + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + if(formDBInfos.size() > 0) { + std::sort(formDBInfos.begin(), formDBInfos.end(), [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { + return formDBInfoA.formId < formDBInfoB.formId; + }); + FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos); + return ERR_OK; + } else { + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) const +{ + APP_LOGI("%{public}s called.", __func__); + std::vector formRecordInfos; + if (FormDataMgr::GetInstance().GetFormRecord(bundleName, formRecordInfos)) { + FormDumpMgr::GetInstance().DumpFormInfos(formRecordInfos, formInfos); + return ERR_OK; + } else { + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const +{ + APP_LOGI("%{public}s called.", __func__); + int reply = ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + + FormRecord formRecord; + if (FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { + FormDumpMgr::GetInstance().DumpFormInfo(formRecord, formInfo); + reply = ERR_OK; + } + + FormHostRecord formHostRecord; + if (FormDataMgr::GetInstance().GetFormHostRecord(formId, formHostRecord)) { + FormDumpMgr::GetInstance().DumpFormHostInfo(formHostRecord, formInfo); + reply = ERR_OK; + } + + return reply; +} +/** + * @brief Get form configure info. + * @param want The want of the request. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetFormConfigInfo(const Want &want, FormItemInfo &formConfigInfo) +{ + APP_LOGD("GetFormConfigInfo start."); + BundleInfo bundleInfo; + std::string packageName; + + ErrCode errCode = GetBundleInfo(want, bundleInfo, packageName); + if (errCode != ERR_OK) { + APP_LOGE("addForm find bundle info failed"); + return errCode; + } + + FormInfo formInfo; + errCode = GetFormInfo(want, formInfo); + if (errCode != ERR_OK) { + APP_LOGE("addForm can not find target form info"); + return errCode; + } + + errCode = GetFormItemInfo(want, bundleInfo, formInfo, formConfigInfo); + if (errCode != ERR_OK) { + APP_LOGE("get form item info failed."); + return errCode; + } + formConfigInfo.SetPackageName(packageName); + + APP_LOGD("GetFormConfigInfo end."); + return ERR_OK; +} +/** + * @brief Allocate form by formId. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, const sptr &callerToken, +const WantParams &wantParams, FormJsInfo &formInfo) +{ + int64_t formId = PaddingUDIDHash(info.GetFormId()); + FormRecord record; + bool hasRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record); + if (hasRecord && record.formTempFlg) { + APP_LOGE("%{public}s, addForm can not acquire temp form when select form id", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + if (hasRecord && FormDataMgr::GetInstance().IsCallingUidValid(record.formUserUids)) { + if (!info.IsMatch(record)) { + APP_LOGE("%{public}s, formId and item info not match:%{public}lld", __func__, formId); + return ERR_CFG_NOT_MATCH_ID; + } + return AddExistFormRecord(info, callerToken, record, formId, wantParams); + } + + // find in db but not in cache + FormRecord dbRecord; + ErrCode getDbRet = FormDbCache::GetInstance().GetDBRecord(formId, dbRecord); + if (getDbRet == ERR_OK && FormDataMgr::GetInstance().IsCallingUidValid(dbRecord.formUserUids)) { + return AddNewFormRecord(info, formId, callerToken, wantParams, formInfo); + } + + APP_LOGI("%{public}s, addForm no such form %{public}lld", __func__, formId); + + // delete form data in provider + FormRecord delRecord; + delRecord.bundleName = info.GetProviderBundleName(); + delRecord.abilityName = info.GetAbilityName(); + FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, delRecord); + + return ERR_NOT_EXIST_ID; +} +int64_t FormMgrAdapter::PaddingUDIDHash(const int64_t formId) const +{ + // Compatible with int form id. + if ((formId & 0xffffffff00000000L) == 0) { + return FormDataMgr::GetInstance().GetUdidHash() | formId; + } + return formId; +} +ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr &callerToken, + const FormRecord &record, const int64_t formId, const WantParams &wantParams) +{ + APP_LOGI("%{public}s call, formId:%{public}lld", __func__, formId); + // allot form host record + int callingUid = IPCSkeleton::GetCallingUid(); + bool isCreated = FormDataMgr::GetInstance().AllotFormHostRecord(info, callerToken, formId, callingUid); + if (!isCreated) { + APP_LOGE("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + FormRecord newRecord(record); + if (newRecord.needRefresh) { + newRecord.isInited = false; + FormDataMgr::GetInstance().SetFormCacheInited(formId, false); + // acquire formInfo from provider + ErrCode errorCode = AcquireProviderFormInfoAsync(formId, info, wantParams); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__); + return errorCode; + } + } + + // Add new form user uid. + FormDataMgr::GetInstance().AddFormUserUid(formId, callingUid); + if (std::find(newRecord.formUserUids.begin(), newRecord.formUserUids.end(), callingUid) == + newRecord.formUserUids.end()) { + newRecord.formUserUids.emplace_back(callingUid); + } + + // start update timer + if (ErrCode errorCode = AddFormTimer(newRecord); errorCode != ERR_OK) { + return errorCode; + } + + if (!newRecord.formTempFlg) { + return FormDbCache::GetInstance().UpdateDBRecord(formId, newRecord); + } + return ERR_OK; +} +/** + * @brief Allocate form by form configure info. + * @param info Form configure info. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info, const sptr &callerToken, +const WantParams &wantParams, FormJsInfo &formInfo) +{ + // generate formId + int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId(); + if (newFormId < 0) { + APP_LOGE("%{public}s fail, generateFormId no invalid formId", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + APP_LOGD("newFormId:%{public}lld", newFormId); + + return AddNewFormRecord(info, newFormId, callerToken, wantParams, formInfo); +} + +/** + * @brief Add new form record. + * @param info Form configure info. + * @param formId The form id. + * @param callerToken Caller ability token. + * @param wantParams WantParams of the request. + * @param formInfo Form info for form host. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AddNewFormRecord(const FormItemInfo &info, const int64_t formId, + const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) +{ + APP_LOGI("%{public}s start", __func__); + FormItemInfo newInfo(info); + newInfo.SetFormId(formId); + // allot form host record + int callingUid = IPCSkeleton::GetCallingUid(); + if (!FormDataMgr::GetInstance().AllotFormHostRecord(newInfo, callerToken, formId, callingUid)) { + APP_LOGE("%{public}s fail, AllotFormHostRecord failed when no matched formRecord", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + // allot form record + FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(newInfo, callingUid); + + // acquire formInfo from provider + if (ErrCode errorCode = AcquireProviderFormInfoAsync(formId, newInfo, wantParams); errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, AcquireProviderFormInfoAsync failed", __func__); + return errorCode; + } + + // create form info for js + FormDataMgr::GetInstance().CreateFormInfo(formId, formRecord, formInfo); + + // storage info + if (!newInfo.IsTemporaryForm()) { + if (ErrCode errorCode = FormDbCache::GetInstance().UpdateDBRecord(formId, formRecord); errorCode != ERR_OK) { + return errorCode; + } + } + + // start update timer + return AddFormTimer(formRecord); +} + +/** + * @brief Add form timer. + * @param formRecord Form information. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AddFormTimer(const FormRecord &formRecord) +{ + APP_LOGI("%{public}s start", __func__); + if (formRecord.isEnableUpdate && !formRecord.formTempFlg) { + bool timerRet = false; + if (formRecord.updateDuration > 0) { + timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, formRecord.updateDuration); + } else { + timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, formRecord.updateAtHour, + formRecord.updateAtMin); + } + if (!timerRet) { + APP_LOGE("%{public}s fail, add form timer failed", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } + APP_LOGI("%{public}s end", __func__); + return ERR_OK; +} + +/** + * @brief Send event notify to form provider. The event notify type include FORM_VISIBLE and FORM_INVISIBLE. + * + * @param providerKey The provider key string which consists of the provider bundle name and ability name. + * @param formIdsByProvider The vector of form Ids which have the same provider. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const std::vector &formIdsByProvider, + const int32_t formVisibleType) +{ + APP_LOGI("%{public}s called.", __func__); + + sptr formEventNotifyConnection = new FormEventNotifyConnection(formIdsByProvider, + formVisibleType); + Want connectWant; + connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + size_t position = providerKey.find(Constants::NAME_DELIMITER); + connectWant.SetElementName(providerKey.substr(0, position), + providerKey.substr(position + Constants::NAME_DELIMITER.size())); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formEventNotifyConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return errorCode; + } + + return ERR_OK; +} + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the form. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId, const FormItemInfo &info, +const WantParams &wantParams) +{ + if (formId <= 0) { + APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + sptr formAcquireConnection + = new FormAcquireConnection(formId, info, wantParams); + Want want; + want.SetElementName(info.GetProviderBundleName(), info.GetAbilityName()); + want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + return FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection); +} + +/** + * @brief Get bundle info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param packageName Package name. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundleInfo, std::string &packageName) +{ + APP_LOGD("GetBundleMgr start."); + std::string bundleName = want.GetElement().GetBundleName(); + std::string abilityName = want.GetElement().GetAbilityName(); + std::string deviceId = want.GetElement().GetDeviceID(); + std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY); + if (bundleName.empty() || abilityName.empty() || moduleName.empty()) { + APP_LOGE("GetBundleInfo bundleName or abilityName or moduleName is invalid"); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("GetBundleMgr, failed to get IBundleMgr."); + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + if (iBundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo) != true) { + APP_LOGE("GetBundleInfo, failed to get bundle info."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + + bool moduleExist = false; + for (const auto &moduleInfo : bundleInfo.moduleNames) { + APP_LOGD("bundleInfo.moduleNames, module name:%{public}s", moduleInfo.c_str()); + if (moduleInfo.compare(moduleName) == 0) { + moduleExist = true; + break; + } + } + if (!moduleExist) { + APP_LOGE("GetBundleInfo no such module, name:%{public}s", moduleName.c_str()); + return ERR_APPEXECFWK_FORM_NO_SUCH_MODULE; + } + + for (const auto &abilityInfo : bundleInfo.abilityInfos) { + // if (abilityInfo.moduleName.compare(GetFullClassName(abilityInfo.package, abilityName)) == 0) { + // packageName = abilityInfo.package; + // break; + // } + if (abilityInfo.deviceId == deviceId) { + packageName = abilityInfo.package; + break; + } + } + + if (packageName.empty()) { + APP_LOGE("GetBundleInfo can not find target ability %{public}s", abilityName.c_str()); + return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; + } + APP_LOGD("GetBundleMgr end."); + return ERR_OK; +} +/** + * @brief Get form info. + * @param want The want of the request. + * @param packageName Package name. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo) +{ + APP_LOGD("GetFormInfo start."); + std::string bundleName = want.GetElement().GetBundleName(); + std::string abilityName = want.GetElement().GetAbilityName(); + std::string moduleName = want.GetStringParam(Constants::PARAM_MODULE_NAME_KEY); + if (bundleName.empty() || abilityName.empty() || moduleName.empty()) { + APP_LOGE("addForm bundleName or abilityName or moduleName is invalid"); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("GetFormInfo, failed to get IBundleMgr."); + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + std::vector formInfos; + if (iBundleMgr->GetFormsInfoByModule(bundleName, moduleName, formInfos) == false) { + APP_LOGE("GetFormsInfoByModule, failed to get form config info."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + + std::string formName = want.GetStringParam(Constants::PARAM_FORM_NAME_KEY); + if (formName.empty()) { + for (const auto &form : formInfos) { + if (form.defaultFlag) { + formInfo = form; + APP_LOGD("GetFormInfo end."); + return ERR_OK; + } + } + } else { + for (const auto &form : formInfos) { + if (form.name == formName) { + formInfo = form; + APP_LOGD("GetFormInfo end."); + return ERR_OK; + } + } + } + APP_LOGE("failed to get form info failed."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; +} +/** + * @brief Get form configure info. + * @param want The want of the request. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param formItemInfo Form configure info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormMgrAdapter::GetFormItemInfo(const AAFwk::Want &want, const BundleInfo &bundleInfo, + const FormInfo &formInfo, FormItemInfo &formItemInfo) +{ + APP_LOGD("GetFormItemInfo start."); + int32_t dimensionId = want.GetIntParam(Constants::PARAM_FORM_DIMENSION_KEY, formInfo.defaultDimension); + if (!IsDimensionValid(formInfo, dimensionId)) { + APP_LOGE("addForm, dimension is not valid"); + return ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION; + } + + // int32_t orientation = want.GetIntParam(Constants::PARAM_FORM_ORIENTATION_KEY, Constants::ORIENTATION_PORTRAIT); + // if (orientation != Constants::ORIENTATION_PORTRAIT && orientation != Constants::ORIENTATION_LANDSCAPE) { + // orientation = Constants::ORIENTATION_PORTRAIT; + // } + + if (ErrCode ret = CreateFormItemInfo(bundleInfo, formInfo, formItemInfo); ret != ERR_OK) { + return ret; + } + // formItemInfo.SetFormId(formId); + // formItemInfo.orientation_ = orientation; + formItemInfo.SetSpecificationId(dimensionId); + formItemInfo.SetTemporaryFlag(want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false)); + + APP_LOGD("GetFormItemInfo end."); + return ERR_OK; +} +/** + * @brief Dimension valid check. + * @param formInfo Form info. + * @param dimensionId Dimension id. + * @return Returns true on success, false on failure. + */ +bool FormMgrAdapter::IsDimensionValid(const FormInfo &formInfo, int dimensionId) const +{ + if (formInfo.supportDimensions.empty()) { + APP_LOGE("Js form, no support dimension."); + return false; + } + + for (size_t i = 0; i < formInfo.supportDimensions.size() && i < Constants::MAX_LAYOUT; i++) { + int supportDimensionId = formInfo.supportDimensions[i]; + if (supportDimensionId == dimensionId) { + return true; + } + } + + APP_LOGE("No matched dimension found."); + return false; +} +/** + * @brief Create form configure info. + * @param bundleInfo Bundle info. + * @param formInfo Form info. + * @param itemInfo Form configure info. + */ +ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, const FormInfo &formInfo, +FormItemInfo &itemInfo) +{ + itemInfo.SetProviderBundleName(bundleInfo.name); + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("GetFormInfo, failed to get IBundleMgr."); + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + std::string hostBundleName {}; + if (!iBundleMgr->GetBundleNameForUid(IPCSkeleton::GetCallingUid(), hostBundleName)) { + APP_LOGE("GetFormsInfoByModule, failed to get form config info."); + return ERR_APPEXECFWK_FORM_GET_INFO_FAILED; + } + itemInfo.SetHostBundleName(hostBundleName); + itemInfo.SetAbilityName(formInfo.abilityName); + itemInfo.SetModuleName(formInfo.name); // formInfo.moduleName: bundleMagr do not set + itemInfo.SetFormName(formInfo.name); + itemInfo.SetEnableUpdateFlag(formInfo.updateEnabled); + itemInfo.SetUpdateDuration(formInfo.updateDuration); + itemInfo.SetScheduledUpdateTime(formInfo.scheduledUpateTime); + itemInfo.SetJsComponentName(formInfo.jsComponentName); + itemInfo.SetFormVisibleNotify(formInfo.formVisibleNotify); + + for (const auto &abilityInfo : bundleInfo.abilityInfos) { + if (abilityInfo.name == formInfo.abilityName) { + itemInfo.SetAbilityModuleName(abilityInfo.moduleName); + } + } + + for (const auto &item : bundleInfo.applicationInfo.moduleInfos) { + if (formInfo.moduleName == item.moduleName) { + itemInfo.AddHapSourceDirs(item.moduleSourceDir); + } + itemInfo.AddModuleInfo(item.moduleName, item.moduleSourceDir); + } + return ERR_OK; +} + +/** + * @brief set next refresh time. + * @param formId The id of the form. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + APP_LOGI("%{public}s begin here, formId:%{public}lld,nextTime:%{public}lld", __func__, formId, nextTime); + if (formId <= 0) { + APP_LOGE("%{public}s form formId or bundleName is invalid", __func__); + return ERR_FORM_INVALID_PARAM; + } + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + + std::string bundleName; + if (!GetBundleName(bundleName)) { + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGE("%{public}s, not found in formrecord.", __func__); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + // check bundleName + if (bundleName != formRecord.bundleName) { + APP_LOGE("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str()); + return ERR_OPERATION_FORM_NOT_SELF; + } + + return SetNextRefreshtTimeLocked(matchedFormId, nextTime); +} + +/** + * @brief get bundleName. + * @param bundleName for output. + * @return Returns true on success, others on failure. + */ +bool FormMgrAdapter::GetBundleName(std::string &bundleName) +{ + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s, failed to get IBundleMgr.", __func__); + return false; + } + + int32_t uid = IPCSkeleton::GetCallingUid(); + if (!iBundleMgr->CheckIsSystemAppByUid(uid)) { + APP_LOGE("%{public}s fail, form is not system app. uid:%{public}d", __func__, uid); + return false; + } + + bool result = iBundleMgr->GetBundleNameForUid(uid, bundleName); + if (!result || bundleName.empty()) { + APP_LOGE("%{public}s failed, cannot get bundle name by uid:%{public}d", __func__, uid); + return false; + } + return true; +} + +/** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::SetNextRefreshtTimeLocked(const int64_t formId, const int64_t nextTime) +{ + APP_LOGE("SetNextRefreshtTimeLocked."); + int32_t timerRefreshedCount = FormTimerMgr::GetInstance().GetRefreshCount(formId); + if (timerRefreshedCount >= Constants::LIMIT_COUNT) { + APP_LOGE("%{public}s, already refresh times:%{public}d", __func__, timerRefreshedCount); + FormTimerMgr::GetInstance().MarkRemind(formId); + return ERR_MAX_REFRESH; + } + + if (!FormTimerMgr::GetInstance().SetNextRefreshTime(formId, nextTime)) { + APP_LOGE("%{public}s failed", __func__); + return ERR_CODE_COMMON; + } + + return ERR_OK; +} + +/** + * @brief set next refresht time locked. + * @param formId The form's id. + * @param bundleName Provider ability bundleName. + * @return Returns true or false. + */ +bool FormMgrAdapter::IsUpdateValid(const int64_t formId, const std::string &bundleName) +{ + if (formId <= 0 || bundleName.empty()) { + return false; + } + return true; +} + +/** + * @brief enable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::EnableUpdateForm(const std::vector formIDs, const sptr &callerToken) +{ + APP_LOGI("enableUpdateForm"); + return HandleUpdateFormFlag(formIDs, callerToken, true); +} + +/** + * @brief disable update form. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrAdapter::DisableUpdateForm(const std::vector formIDs, const sptr &callerToken) +{ + APP_LOGI("disableUpdateForm"); + return HandleUpdateFormFlag(formIDs, callerToken, false); +} + +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgrAdapter::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + if (formId <= 0) { + APP_LOGE("%{public}s form formId or bundleName is invalid", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (callerToken == nullptr) { + APP_LOGE("%{public}s failed, callerToken can not be NULL", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (!want.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + APP_LOGE("%{public}s failed, message info is not exist", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + FormRecord record; + bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record); + if (!bGetRecord) { + APP_LOGE("%{public}s fail, not exist such form:%{public}lld", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + + FormHostRecord formHostRecord; + bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); + if (!isHostExist) { + APP_LOGE("%{public}s failed, cannot find target client.", __func__); + return ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST; + } + + if (!formHostRecord.Contains(matchedFormId)) { + APP_LOGE("%{public}s failed, form is not self-owned.", __func__); + return ERR_OPERATION_FORM_NOT_SELF; + } + + APP_LOGI("%{public}s, find target client.", __func__); + return FormProviderMgr::GetInstance().MessageEvent(matchedFormId, record, want); +} + +int FormMgrAdapter::HandleUpdateFormFlag(std::vector formIds, const sptr &callerToken, +bool flag) +{ + APP_LOGI("%{public}s called.", __func__); + if (formIds.empty() || callerToken == nullptr) { + APP_LOGE("%{public}s, invalid param", __func__); + return ERR_FORM_INVALID_PARAM; + } + std::vector refreshForms; + int errCode = FormDataMgr::GetInstance().UpdateHostFormFlag(formIds, callerToken, flag, refreshForms); + if (errCode == ERR_OK && refreshForms.size() > 0) { + for (const int64_t id : refreshForms) { + APP_LOGI("%{public}s, formRecord need refresh: %{public}lld", __func__, id); + Want want; + FormProviderMgr::GetInstance().RefreshForm(id, want); + } + } + return errCode; +} + +/** + * @brief handle update form flag. + * @param formIDs The id of the forms. + * @param callerToken Caller ability token. + * @param flag form flag. + * @return Returns ERR_OK on success, others on failure. + */ +bool FormMgrAdapter::IsFormCached(const FormRecord record) { + if (record.versionUpgrade) { + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_mgr_service.cpp b/services/formmgr/src/form_mgr_service.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8eb194ba678001d6fb32a7fb9bba2e716bad3a77 --- /dev/null +++ b/services/formmgr/src/form_mgr_service.cpp @@ -0,0 +1,388 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_bms_helper.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_mgr_service.h" +#include "form_task_mgr.h" +#include "form_timer_mgr.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std::chrono; +using PermissionKit = OHOS::Security::Permission::PermissionKit; +using PermissionState = OHOS::Security::Permission::PermissionState; + +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +const std::string NAME_FORM_MGR_SERVICE = "FormMgrService"; + +FormMgrService::FormMgrService() + : SystemAbility(FORM_MGR_SERVICE_ID, true), + state_(ServiceRunningState::STATE_NOT_START), + runner_(nullptr), + handler_(nullptr), + formMgrAdapter_(std::make_unique()) +{ +} + +FormMgrService::~FormMgrService() +{} + +bool FormMgrService::IsReady() const +{ + if (state_ != ServiceRunningState::STATE_RUNNING) { + return false; + } + if (!handler_) { + APP_LOGE("%{public}s fail, handler is null", __func__); + return false; + } + + return true; +} + +/** + * @brief Add form with want, send want to form manager service. + * @param formId The Id of the forms to add. + * @param want The want of the form to add. + * @param callerToken Caller ability token. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, add form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + return formMgrAdapter_->AddForm(formId, want, callerToken, formInfo); +} + +/** + * @brief Delete forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to delete. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DeleteForm(const int64_t formId, const sptr &callerToken) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, delete form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return formMgrAdapter_->DeleteForm(formId, callerToken); +} + +/** + * @brief Release forms with formIds, send formIds to form manager service. + * @param formId The Id of the forms to release. + * @param callerToken Caller ability token. + * @param delCache Delete Cache or not. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::ReleaseForm(const int64_t formId, const sptr &callerToken, const bool delCache) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, release form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return formMgrAdapter_->ReleaseForm(formId, callerToken, delCache); +} + +/** + * @brief Update form with formId, send formId to form manager service. + * @param formId The Id of the form to update. + * @param bundleName Provider ability bundleName. + * @param formBindingData Form binding data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::UpdateForm(const int64_t formId, const std::string &bundleName, +const FormProviderData &formBindingData) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, update form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + return formMgrAdapter_->UpdateForm(formId, bundleName, formBindingData); +} + +/** + * @brief Request form with formId and want, send formId and want to form manager service. + * @param formId The Id of the form to update. + * @param callerToken Caller ability token. + * @param want The want of the form to add. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::RequestForm(const int64_t formId, const sptr &callerToken, const Want &want) +{ + APP_LOGI("%{public}s called.", __func__); + + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, request form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return formMgrAdapter_->RequestForm(formId, callerToken, want); +} + +/** + * @brief set next refresh time. + * @param formId The id of the form. + * @param bundleManager the bundle manager ipc object. + * @param nextTime next refresh time. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) +{ + APP_LOGI("%{public}s called.", __func__); + + return formMgrAdapter_->SetNextRefreshTime(formId, nextTime); +} + + +/** + * @brief Form visible/invisible notify, send formIds to form manager service. + * @param formIds The Id list of the forms to notify. + * @param callerToken Caller ability token. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::NotifyWhetherVisibleForms(const std::vector &formIds, +const sptr &callerToken, const int32_t formVisibleType) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, event notify visible permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return formMgrAdapter_->NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); +} + +/** + * @brief temp form to normal form. + * @param formId The Id of the form. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::CastTempForm(const int64_t formId, const sptr &callerToken) +{ + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, cast temp form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return formMgrAdapter_->CastTempForm(formId, callerToken); +} + +/** + * @brief lifecycle update. + * @param formIds formIds of hostclient. + * @param callerToken Caller ability token. + * @param updateType update type,enable or disable. + * @return Returns true on success, false on failure. + */ +int FormMgrService::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, +const int32_t updateType) +{ + APP_LOGI("lifecycleUpdate."); + + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, delete form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + if (updateType == ENABLE_FORM_UPDATE) { + return formMgrAdapter_->EnableUpdateForm(formIds, callerToken); + } else { + return formMgrAdapter_->DisableUpdateForm(formIds, callerToken); + } +} +/** + * @brief Dump all of form storage infos. + * @param formInfos All of form storage infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DumpStorageFormInfos(std::string &formInfos) +{ + return formMgrAdapter_->DumpStorageFormInfos(formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param bundleName The bundle name of form provider. + * @param formInfos Form infos. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) +{ + return formMgrAdapter_->DumpFormInfoByBundleName(bundleName, formInfos); +} +/** + * @brief Dump form info by a bundle name. + * @param formId The id of the form. + * @param formInfo Form info. + * @return Returns ERR_OK on success, others on failure. + */ +int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) +{ + return formMgrAdapter_->DumpFormInfoByFormId(formId, formInfo); +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param want information passed to supplier. + * @param callerToken Caller ability token. + * @return Returns true if execute success, false otherwise. + */ +int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken) +{ + APP_LOGI("%{public}s called.", __func__); + + if (!CheckFormPermission()) { + APP_LOGE("%{public}s fail, request form permission denied", __func__); + return ERR_APPEXECFWK_FORM_PERMISSION_DENY; + } + + return formMgrAdapter_->MessageEvent(formId, want, callerToken); +} +/** + * @brief Start envent for the form manager service. + */ +void FormMgrService::OnStart() +{ + if (state_ == ServiceRunningState::STATE_RUNNING) { + APP_LOGW("%{public}s fail, Failed to start service since it's already running", __func__); + return; + } + + APP_LOGI("Form Mgr Service start..."); + ErrCode errCode = Init(); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s fail, Failed to init, errCode: %{public}08x", __func__, errCode); + return; + } + + state_ = ServiceRunningState::STATE_RUNNING; + + APP_LOGI("Form Mgr Service start success."); +} +/** + * @brief Stop envent for the form manager service. + */ +void FormMgrService::OnStop() +{ + APP_LOGI("stop service"); + + state_ = ServiceRunningState::STATE_NOT_START; + + if (handler_) { + handler_.reset(); + } + + if (runner_) { + runner_.reset(); + } +} +/** + * @brief initialization of form manager service. + */ +ErrCode FormMgrService::Init() +{ + runner_ = EventRunner::Create(NAME_FORM_MGR_SERVICE); + if (!runner_) { + APP_LOGE("%{public}s fail, Failed to init due to create runner error", __func__); + return ERR_INVALID_OPERATION; + } + handler_ = std::make_shared(runner_); + if (!handler_) { + APP_LOGE("%{public}s fail, Failed to init due to create handler error", __func__); + return ERR_INVALID_OPERATION; + } + FormTaskMgr::GetInstance().SetEventHandler(handler_); + /* Publish service maybe failed, so we need call this function at the last, + * so it can't affect the TDD test program */ + bool ret = Publish(DelayedSingleton::GetInstance().get()); + if (!ret) { + APP_LOGE("%{public}s fail, FormMgrService::Init Publish failed!", __func__); + return ERR_INVALID_OPERATION; + } + + FormDbCache::GetInstance().Start(); + + APP_LOGI("init success"); + return ERR_OK; +} +/** + * @brief Permission check by callingUid. + * @param formId the id of the form. + * @return Returns true on success, false on failure. + */ +bool FormMgrService::CheckFormPermission() +{ + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + APP_LOGE("%{public}s, failed to get IBundleMgr.", __func__); + return false; + } + + int32_t uid = IPCSkeleton::GetCallingUid(); + if (!iBundleMgr->CheckIsSystemAppByUid(uid)) { + APP_LOGE("%{public}s fail, form is not system app. uid:%{public}d", __func__, uid); + return false; + } + + std::string bundleName; + bool result = iBundleMgr->GetBundleNameForUid(uid, bundleName); + if (!result || bundleName.empty()) { + APP_LOGE("%{public}s failed, cannot get bundle name by uid:%{public}d", __func__, uid); + return false; + } + + return CheckFormPermission(bundleName); +} + +bool FormMgrService::CheckFormPermission(const std::string &bundleName) const +{ + if (bundleName.empty()) { + APP_LOGE("%{public}s fail, bundleName can not be empty", __func__); + return false; + } + int result = PermissionKit::VerifyPermission(bundleName, Constants::PERMISSION_REQUIRE_FORM, 0); + if (result != PermissionState::PERMISSION_GRANTED) { + APP_LOGW("permission = %{public}s, bundleName = %{public}s, result = %{public}d", + Constants::PERMISSION_REQUIRE_FORM.c_str(), bundleName.c_str(), result); + } + return result == PermissionState::PERMISSION_GRANTED; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_msg_event_connection.cpp b/services/formmgr/src/form_msg_event_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..513b44865cd72cb50972bb0457acfb26bd8e73b1 --- /dev/null +++ b/services/formmgr/src/form_msg_event_connection.cpp @@ -0,0 +1,64 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_msg_event_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormMsgEventConnection::FormMsgEventConnection(const int64_t formId, const Want& want) + :formId_(formId), + want_(want) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormMsgEventConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}lld, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + Want eventWant = Want(want_); + eventWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostFormEventTask(formId_, message, eventWant, remoteObject); + } else { + APP_LOGE("%{public}s error, message info is not exist", __func__); + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_provider_mgr.cpp b/services/formmgr/src/form_provider_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ef53c1d9d06ae5cc3936b73455feeaa19b0c9b1 --- /dev/null +++ b/services/formmgr/src/form_provider_mgr.cpp @@ -0,0 +1,369 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ams_helper.h" +#include "form_batch_delete_connection.h" +#include "form_cache_mgr.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_delete_connection.h" +#include "form_msg_event_connection.h" +#include "form_provider_mgr.h" +#include "form_record.h" +#include "form_refresh_connection.h" +#include "form_timer_mgr.h" +#include "power_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +FormProviderMgr::FormProviderMgr(){} +FormProviderMgr::~FormProviderMgr(){} +/** + * @brief handle for acquire back from ams. + * @param formId The id of the form. + * @param formProviderInfo provider form info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::AcquireForm(const int64_t formId, const FormProviderInfo &formProviderInfo) +{ + APP_LOGD("%{public}s start, formId:%{public}lld", __func__, formId); + + if (formId <= 0) { + APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); + return ERR_FORM_INVALID_PARAM; + } + + FormRecord formRecord; + bool isGetFormRecord = FormDataMgr::GetInstance().GetFormRecord(formId, formRecord); + if (!isGetFormRecord) { + APP_LOGE("%{public}s fail, not exist such form, formId:%{public}lld", __func__, formId); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + + FormHostRecord clientHost; + bool isGetFormHostRecord = FormDataMgr::GetInstance().GetFormHostRecord(formId, clientHost); + if (!isGetFormHostRecord) { + APP_LOGE("%{public}s fail, clientHost is null", __func__); + return ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST; + } + + if (formRecord.isInited) { + if (IsFormCached(formRecord)) { + if (clientHost.Contains(formId)) { + formRecord.formProviderInfo = formProviderInfo; + clientHost.OnAcquire(formId, formRecord); + } + } else { + Want want; + RefreshForm(formId, want); + } + return ERR_OK; + } + formRecord.isInited = true; + formRecord.needRefresh = false; + FormDataMgr::GetInstance().SetFormCacheInited(formId, true); + + if (clientHost.Contains(formId)) { + formRecord.formProviderInfo = formProviderInfo; + clientHost.OnAcquire(formId, formRecord); + } + + // we do not cache when data size is over 1k + std::string jsonData = formProviderInfo.GetFormDataString(); // get json data + APP_LOGD("%{public}s , jsonData is %{public}s.", __func__, jsonData.c_str()); + if (jsonData.size() <= Constants::MAX_FORM_DATA_SIZE) { + APP_LOGW("%{public}s, acquire js card, cache the card", __func__); + FormCacheMgr::GetInstance().AddData(formId, formProviderInfo.GetFormDataString()); + } + return ERR_OK; +} + +/** + * @brief Refresh form. + * + * @param formId The form id. + * @param want The want of the form to request. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::RefreshForm(const int64_t formId, const Want &want) +{ + APP_LOGI("%{public}s called, formId:%{public}lld.", __func__, formId); + FormRecord record; + bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record); + if (!bGetRecord) { + APP_LOGE("%{public}s fail, not exist such form:%{public}lld", __func__, formId); + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; + } + + bool isTimerRefresh = want.GetBoolParam(Constants::KEY_IS_TIMER, false); + Want newWant(want); + newWant.RemoveParam(Constants::KEY_IS_TIMER); + + if (isTimerRefresh) { + FormDataMgr::GetInstance().SetCountTimerRefresh(formId, true); + } + + bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); + if (!screenOnFlag) { + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + APP_LOGE("%{public}s fail, screen off, set refresh flag, do not refresh now", __func__); + return ERR_OK; + } + + bool needRefresh = FormDataMgr::GetInstance().IsEnableRefresh(formId); + if (!needRefresh) { + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + APP_LOGE("%{public}s fail, no one needReresh, set refresh flag, do not refresh now", __func__); + return ERR_OK; + } + + FormRecord refreshRecord = GetFormAbilityInfo(record); + refreshRecord.isInited = record.isInited; + refreshRecord.versionUpgrade = record.versionUpgrade; + refreshRecord.isCountTimerRefresh = isTimerRefresh; + return ConnectAmsForRefresh(formId, refreshRecord, newWant, isTimerRefresh); +} + +/** + * @brief Connect ams for refresh form + * + * @param formId The form id. + * @param record Form data. + * @param want The want of the form. + * @param isTimerRefresh The flag of timer refresh. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::ConnectAmsForRefresh(const int64_t formId, const FormRecord &record, const Want &want, +const bool isTimerRefresh) +{ + APP_LOGD("%{public}s called, bundleName:%{public}s, abilityName:%{public}s.", + __func__, record.bundleName.c_str(), record.abilityName.c_str()); + + sptr formRefreshConnection = new FormRefreshConnection(formId, want); + Want connectWant; + connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + connectWant.SetElementName(record.bundleName, record.abilityName); + + if (isTimerRefresh) { + if (!FormTimerMgr::GetInstance().IsLimiterEnableRefresh(formId)) { + APP_LOGE("%{public}s, timer refresh, already limit.", __func__); + return ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL; + } + } + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formRefreshConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return errorCode; + } + + if (record.isCountTimerRefresh) { + IncreaseTimerRefreshCount(formId); + } + + return ERR_OK; +} + +/** + * @brief Notify provider form delete. + * @param formId The form id. + * @param record Form information. + * @return Function result and has other host flag. + */ +ErrCode FormProviderMgr::NotifyProviderFormDelete(const int64_t formId, const FormRecord &formRecord) +{ + if (formRecord.abilityName.empty()) { + APP_LOGE("%{public}s, formRecord.abilityName is empty.", __func__); + return ERR_CODE_COMMON; + } + + if (formRecord.bundleName.empty()) { + APP_LOGE("%{public}s, formRecord.bundleName is empty.", __func__); + return ERR_CODE_COMMON; + } + + APP_LOGD("%{public}s, connectAbility,bundleName:%{public}s, abilityName:%{public}s", + __func__, formRecord.bundleName.c_str(), formRecord.abilityName.c_str()); + sptr formDeleteConnection = new FormDeleteConnection(formId); + Want want; + want.SetElementName(formRecord.bundleName, formRecord.abilityName); + want.SetFlags(Want::FLAG_ABILITY_FORM_ENABLED); + return FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection); +} + +/** + * @brief Notify provider forms batch delete. + * @param bundleName BundleName. + * @param bundleName AbilityName. + * @param formIds form id list. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundleName, const std::string &abilityName, +const std::set &formIds) +{ + if (abilityName.empty()) { + APP_LOGE("%{public}s error, abilityName is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (bundleName.empty()) { + APP_LOGE("%{public}s error, bundleName is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + APP_LOGD("%{public}s, bundleName:%{public}s, abilityName:%{public}s", __func__, bundleName.c_str(), + abilityName.c_str()); + sptr batchDeleteConnection = new FormBatchDeleteConnection(formIds); + Want want; + want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + want.SetElementName(bundleName, abilityName); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, batchDeleteConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return errorCode; + } + return ERR_OK; +} +/** + * @brief Update form. + * @param formId The form's id. + + * @param formProviderData form provider data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::UpdateForm(const int64_t formId, const FormProviderInfo &formProviderInfo) +{ + // check exist and get the formRecord + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { + APP_LOGE("%{public}s error, not exist such form:%{public}lld.", __func__, formId); + return ERR_NOT_EXIST_ID; + } + return UpdateForm(formId, formRecord, formProviderInfo.GetFormData()); +} +/** + * handle for update form event from provider. + * + * @param formId The id of the form. + * @param formRecord The form's record. + * @param formProviderData provider form info. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormProviderMgr::UpdateForm(const int64_t formId, FormRecord &formRecord, +const FormProviderData &formProviderData) +{ + APP_LOGI("%{public}s start", __func__); + + if (formRecord.versionUpgrade) { + formRecord.formProviderInfo.SetFormData(formProviderData); + } else { + nlohmann::json addJsonData = formProviderData.GetData(); + formRecord.formProviderInfo.MergeData(addJsonData); + } + + // formRecord init + formRecord.isInited = true; + formRecord.needRefresh = false; + FormDataMgr::GetInstance().SetFormCacheInited(formId, true); + + // update form for host clients + FormDataMgr::GetInstance().UpdateHostNeedRefresh(formId, true); + + bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); + if (screenOnFlag) { + if (FormDataMgr::GetInstance().UpdateHostForm(formId, formRecord)) { + FormDataMgr::GetInstance().SetVersionUpgrade(formId, false); + } + } + // check if cache data size is less than 1k or not + std::string jsonData = formRecord.formProviderInfo.GetFormDataString(); // get json data + APP_LOGD("%{public}s , jsonData is %{public}s.", __func__, jsonData.c_str()); + if (jsonData.size() <= Constants::MAX_FORM_DATA_SIZE) { + APP_LOGI("%{public}s, updateJsForm, data is less than 1k, cache data.", __func__); + FormCacheMgr::GetInstance().AddData(formId, jsonData); + } + + // the update form is successfully + return ERR_OK; +} +/** + * @brief Process js message event. + * @param formId Indicates the unique id of form. + * @param record Form record. + * @param want information passed to supplier. + * @return Returns true if execute success, false otherwise. + */ +int FormProviderMgr::MessageEvent(const int64_t formId, const FormRecord &record, const Want &want) +{ + APP_LOGI("%{public}s called, formId:%{public}lld.", __func__, formId); + + bool screenOnFlag = PowerMgr::PowerMgrClient::GetInstance().IsScreenOn(); + if (!screenOnFlag) { + APP_LOGW("%{public}s fail, screen off now", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + sptr formMsgEventConnection = new FormMsgEventConnection(formId, want); + Want connectWant; + connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + connectWant.SetElementName(record.bundleName, record.abilityName); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formMsgEventConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return errorCode; + } + + return ERR_OK; +} + +/** + * @brief Increase the timer refresh count. + * + * @param formId The form id. + */ +void FormProviderMgr::IncreaseTimerRefreshCount(const int64_t formId) +{ + FormRecord record; + if (FormDataMgr::GetInstance().GetFormRecord(formId, record)) { + APP_LOGE("%{public}s failed, not exist such form:%{public}lld.", __func__, formId); + return; + } + + if (record.isCountTimerRefresh) { + FormDataMgr::GetInstance().SetCountTimerRefresh(formId, false); + FormTimerMgr::GetInstance().IncreaseRefreshCount(formId); + } +} +FormRecord FormProviderMgr::GetFormAbilityInfo(const FormRecord &record) const +{ + FormRecord newRecord; + newRecord.bundleName = record.bundleName; + newRecord.abilityName = record.abilityName; + + return newRecord; +} + +bool FormProviderMgr::IsFormCached(const FormRecord &record) +{ + if (record.versionUpgrade) { + return false; + } + return FormCacheMgr::GetInstance().IsExist(record.formId); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_refresh_connection.cpp b/services/formmgr/src/form_refresh_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2dd344968de18c7bcefcf36cc946031309bf3c2 --- /dev/null +++ b/services/formmgr/src/form_refresh_connection.cpp @@ -0,0 +1,70 @@ + +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_refresh_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormRefreshConnection::FormRefreshConnection(const int64_t formId, const Want& want) + :formId_(formId), + want_(want) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormRefreshConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}lld, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + // FormTaskMgr::GetInstance()->FireFormEvent(formId, message, BuildDefaultWant(null, this), remoteObject); + } else if (want_.HasParameter(Constants::RECREATE_FORM_KEY)) { + Want cloneWant = Want(want_); + cloneWant.RemoveParam(Constants::RECREATE_FORM_KEY); + cloneWant.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + cloneWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, cloneWant, remoteObject); + } else { + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostRefreshTask(formId_, want, remoteObject); + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_refresh_limiter.cpp b/services/formmgr/src/form_refresh_limiter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..425b723e724c1de8171a12e700f0727e0ee2bcf6 --- /dev/null +++ b/services/formmgr/src/form_refresh_limiter.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_constants.h" +#include "form_refresh_limiter.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Add form limit info by formId. + * @param formId The id of the form. + * @return Returns true on success, false on failure. + */ +bool FormRefreshLimiter::AddItem(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info == limiterMap_.end()) { + LimitInfo limitInfo; + std::pair::iterator, bool> retVal = + limiterMap_.emplace(formId, limitInfo); + APP_LOGI("%{public}s end", __func__); + return retVal.second; + } else { + APP_LOGI("%{public}s end, already exist", __func__); + return true; + } +} +/** + * @brief Delete form limit info by formId. + * @param formId The form id. + */ +void FormRefreshLimiter::DeleteItem(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + limiterMap_.erase(formId); + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Reset limit info. + */ +void FormRefreshLimiter::ResetLimit() +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + for (auto &infoPair : limiterMap_) { + infoPair.second.refreshCount = 0; + infoPair.second.isReported = false; + infoPair.second.remindFlag = false; + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Refresh enable or not. + * @param formId The form id. + * @return Returns ERR_OK on success, others on failure. + */ +bool FormRefreshLimiter::IsEnableRefresh(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + bool isEnable = false; + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + if (info->second.refreshCount < Constants::LIMIT_COUNT) { + isEnable = true; + } + + if (info->second.refreshCount == Constants::LIMIT_COUNT && !info->second.isReported) { + info->second.isReported = true; + APP_LOGI("report refresh to 50 count,formId:%{public}lld", formId); + } + } + APP_LOGI("%{public}s end", __func__); + return isEnable; +} +/** + * @brief Get refresh count. + * @param formId The form id. + * @return refresh count. + */ +int FormRefreshLimiter::GetRefreshCount(const int64_t formId) const +{ + APP_LOGI("%{public}s start", __func__); + // -1 means not added or already removed. + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + return info->second.refreshCount; + } + + APP_LOGI("%{public}s end", __func__); + return -1; +} +/** + * @brief Increase refresh count. + * @param formId The form id. + */ +void FormRefreshLimiter::Increase(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + info->second.refreshCount++; + APP_LOGI("increase,formId:%{public}lld, count:%{public}d", formId, info->second.refreshCount); + if (info->second.refreshCount == Constants::LIMIT_COUNT && !info->second.isReported) { + info->second.isReported = true; + APP_LOGI("report refresh to 50 count,formId:%{public}lld", formId); + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Mark remind flag. + * @param formId The form id. + */ +void FormRefreshLimiter::MarkRemind(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(limiterMutex_); + auto info = limiterMap_.find(formId); + if (info != limiterMap_.end()) { + if (info->second.refreshCount >= Constants::LIMIT_COUNT) { + info->second.remindFlag = true; + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Get remind list. + * @return remind list. + */ +std::vector FormRefreshLimiter::GetRemindList() const +{ + APP_LOGI("%{public}s start", __func__); + std::vector result; + std::lock_guard lock(limiterMutex_); + for (auto &infoPair : limiterMap_) { + if (infoPair.second.remindFlag) { + result.emplace_back(infoPair.first); + } + } + APP_LOGI("%{public}s end", __func__); + return result; +} +/** + * @brief Get remind list and reset limit. + * @return remind list. + */ +std::vector FormRefreshLimiter::GetRemindListAndResetLimit() +{ + APP_LOGI("%{public}s start", __func__); + std::vector result; + std::lock_guard lock(limiterMutex_); + for (auto &infoPair : limiterMap_) { + if (infoPair.second.remindFlag) { + result.emplace_back(infoPair.first); + } + + infoPair.second.refreshCount = 0; + infoPair.second.isReported = false; + infoPair.second.remindFlag = false; + } + APP_LOGI("%{public}s end", __func__); + return result; +} +/** + * @brief Get item count. + * @return Item count. + */ +int FormRefreshLimiter::GetItemCount() const +{ + return limiterMap_.size(); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_storage_mgr.cpp b/services/formmgr/src/form_storage_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43f2b147c976827e4e31b23d4fc4378bd054db41 --- /dev/null +++ b/services/formmgr/src/form_storage_mgr.cpp @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_storage_mgr.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; +const int32_t FORM_DB_DATA_BASE_FILE_PATH_LEN = 255; +} + +// bool FormStorageMgr::KeyToDeviceAndName(const std::string &key, std::string &deviceId, std::string &bundleName) const +// { +// bool ret = false; +// std::vector splitStrs; +// const std::string::size_type EXPECT_SPLIT_SIZE = 2; +// OHOS::SplitStr(key, Constants::FILE_UNDERLINE, splitStrs); +// // the expect split size should be 2. +// // key rule is _ +// if (splitStrs.size() == EXPECT_SPLIT_SIZE) { +// deviceId = splitStrs[0]; +// bundleName = splitStrs[1]; +// ret = true; +// } +// APP_LOGD("key = %{private}s, bundleName = %{public}s", key.c_str(), bundleName.c_str()); +// return ret; +// } + +// void FormStorageMgr::DeviceAndNameToKey( +// const std::string &deviceId, const std::string &bundleName, std::string &key) const +// { +// key.append(deviceId); +// key.append(Constants::FILE_UNDERLINE); +// key.append(bundleName); +// APP_LOGD("key = %{private}s, bundleName = %{public}s", key.c_str(), bundleName.c_str()); +// } + +// bool FormStorageMgr::bool LoadAllData(std::map> &infos) const +// { +// bool ret = false; +// APP_LOGI("load all installed bundle data to map"); + +// std::fstream i(Constants::BUNDLE_DATA_BASE_FILE); +// nlohmann::json jParse; +// if (!i.is_open()) { +// APP_LOGE("failed to open bundle database file"); +// // if file not exist, should create file here +// std::ofstream o(Constants::BUNDLE_DATA_BASE_FILE); +// o.close(); +// return false; +// } +// APP_LOGI("open bundle database file success"); +// i.seekg(0, std::ios::end); +// int len = static_cast(i.tellg()); +// if (len > 0) { +// i.seekg(0, std::ios::beg); +// i >> jParse; +// for (auto &app : jParse.items()) { +// std::map deviceMap; +// for (auto &device : app.value().items()) { +// InnerBundleInfo innerBundleInfo; +// ret = innerBundleInfo.FromJson(device.value()); +// deviceMap.emplace(device.key(), innerBundleInfo); +// } +// auto pair = infos.emplace(app.key(), deviceMap); +// ret = pair.second; +// } +// } +// i.close(); +// return ret; +// } + +/** + * @brief Load form data from fileNamePath to innerFormInfos. + * @param fileNamePath load file path. + * @param innerFormInfos Save form data. + * @return Returns true if the data is successfully loaded; returns false otherwise. + */ +static bool LoadFormDataFile(const char* fileNamePath, std::vector &innerFormInfos) +{ + bool ret = false; + std::ifstream i(fileNamePath); + if (!i.is_open()) { + APP_LOGE("%{public}s, failed to open file[%{public}s]", __func__, fileNamePath); + return false; + } + + nlohmann::json jParse; + i.seekg(0, std::ios::end); + int len = static_cast(i.tellg()); + if (len != 0) { + i.seekg(0, std::ios::beg); + i >> jParse; + for (auto &it : jParse.items()) { + InnerFormInfo innerFormInfo; + if (innerFormInfo.FromJson(it.value())) { + innerFormInfos.emplace_back(innerFormInfo); + } else { + APP_LOGE("%{public}s, failed to parse json, formId[%{public}s]", __func__, it.key().c_str()); + } + } + ret = true; + } else { + APP_LOGE("%{public}s, file[%{public}s] is empty", __func__, fileNamePath); + ret = false; + } + i.close(); + return ret; +} + +/** + * @brief Load all form data from DB to innerFormInfos. + * @param innerFormInfos Storage all form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) const +{ + APP_LOGI("%{public}s called.", __func__); + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + if (dirptr == NULL) { + APP_LOGE("%{public}s, opendir failed, should no formmgr dir", __func__); + return ERR_APPEXECFWK_FORM_JSON_NO_DIR; + } + + struct dirent *ptr; + while ((ptr = readdir(dirptr)) != NULL) { + APP_LOGI("%{public}s, readdir fileName[%{public}s]", __func__, ptr->d_name); + if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { + continue; + } + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%s", FORM_DB_DATA_BASE_FILE_DIR, ptr->d_name); + if (!LoadFormDataFile(fileNamePath, innerFormInfos)) { + APP_LOGE("%{public}s, LoadFormDataFile failed, file[%{public}s]", __func__, ptr->d_name); + } + } + APP_LOGI("%{public}s, readdir over", __func__); + closedir(dirptr); + return ERR_OK; +} + +/** + * @brief Get form data from DB to innerFormInfo with formId. + * @param innerFormInfo Storage form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) const +{ + ErrCode ret = ERR_OK; + APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + std::ifstream i(fileNamePath); + nlohmann::json jParse; + if (!i.is_open()) { + APP_LOGE("%{public}s, open failed, should no this file[%{public}s.json]", __func__, formId.c_str()); + return ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; + } + APP_LOGD("%{public}s, open success file[%{public}s.json]", __func__, formId.c_str()); + i.seekg(0, std::ios::end); + int len = static_cast(i.tellg()); + if (len != 0) { + i.seekg(0, std::ios::beg); + i >> jParse; + auto it = jParse.find(formId); + if (it != jParse.end()) { + if (innerFormInfo.FromJson(it.value()) == false) { + APP_LOGE("%{public}s, fromJson parse failed formId[%{public}s]", __func__, it.key().c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_PARSE_FAIL; + } else { + ret = ERR_OK; + } + } else { + APP_LOGE("%{public}s, not find formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_FIND_FAIL; + } + } else { + APP_LOGE("%{public}s, file is empty formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_FILE_EMPTY; + } + i.close(); + + return ret; +} + +/** + * @brief Save or update the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be save. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::SaveStorageFormInfo(const InnerFormInfo &innerFormInfo) const +{ + APP_LOGI("%{public}s called, formId[%{public}lld]", __func__, innerFormInfo.GetFormId()); + ErrCode ret = ERR_OK; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + if (dirptr == NULL) { + APP_LOGW("%{public}s, failed to open dir", __func__); + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { + APP_LOGE("%{public}s, failed to create dir", __func__); + return ERR_APPEXECFWK_FORM_JSON_CREATE_DIR_FAIL; + } + } else { + closedir(dirptr); + } + char tmpFilePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(tmpFilePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + + std::fstream f(tmpFilePath); + nlohmann::json jParse; + if (!f.is_open()) { + std::ofstream o(tmpFilePath); // if file not exist, should create file here + if (!o.is_open()) { + APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, tmpFilePath); + return ERR_APPEXECFWK_FORM_JSON_NEW_FILE_FAIL; + } + o.close(); + APP_LOGI("%{public}s, touch new file[%{public}s.json]", __func__, formId.c_str()); + f.open(tmpFilePath); + } + bool isExist = f.good(); + if (isExist) { + nlohmann::json innerInfo; + innerFormInfo.ToJson(innerInfo); + f.seekg(0, std::ios::end); + int len = static_cast(f.tellg()); + if (len == 0) { + nlohmann::json formRoot; + formRoot[formId] = innerInfo; + f << formRoot << std::endl; + } else { + APP_LOGE("%{public}s, file[%{public}s.json] is not empty", __func__, formId.c_str()); + } + } else { + APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; + } + f.close(); + return ret; +} + +/** + * @brief Modify the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo) const +{ + APP_LOGI("%{public}s called, formId[%{public}lld]", __func__, innerFormInfo.GetFormId()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%lld.json", FORM_DB_DATA_BASE_FILE_DIR, innerFormInfo.GetFormId()); + + std::ofstream o(fileNamePath, std::ios_base::trunc | std::ios_base::out); + if (!o.is_open()) { + APP_LOGE("%{public}s, open failed file[%{public}s]", __func__, fileNamePath); + return ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; + } + + nlohmann::json innerInfo; + innerFormInfo.ToJson(innerInfo); + nlohmann::json formRoot; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + + formRoot[formId] = innerInfo; + o << formRoot << std::endl; + + o.close(); + return ERR_OK; +} + +/** + * @brief Delete the form data in DB. + * @param formId The form data Id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::DeleteStorageFormInfo(const std::string &formId) const +{ + APP_LOGI("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + + if (std::remove(fileNamePath) != 0) { + APP_LOGE("%{public}s, delete failed file[%{public}s]", __func__, fileNamePath); + return ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL; + } + + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_supply_callback.cpp b/services/formmgr/src/form_supply_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..690c4d5554af0323cb3d89b0d27a4d1a2f13161b --- /dev/null +++ b/services/formmgr/src/form_supply_callback.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ams_helper.h" +#include "form_constants.h" +#include "form_provider_mgr.h" +#include "form_supply_callback.h" +#include "form_util.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +sptr FormSupplyCallback::instance_ = nullptr; +std::mutex FormSupplyCallback::mutex_; + +sptr FormSupplyCallback::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (instance_ == nullptr) { + instance_ = new FormSupplyCallback(); + } + } + return instance_; +} + +/** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnAcquire(const FormProviderInfo &formProviderInfo, const Want &want) +{ + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + int errCode = want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + RemoveConnection(connectId); + return errCode; + } + + int64_t formId = formProviderInfo.GetFormId(); + int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); + APP_LOGD("%{public}s come: %{public}lld, %{public}ld, %{public}d", __func__, + formId, connectId, type); + RemoveConnection(connectId); + + switch (type) { + case Constants::ACQUIRE_TYPE_CREATE_FORM: + return FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo); + case Constants::ACQUIRE_TYPE_RECREATE_FORM: + return FormProviderMgr::GetInstance().UpdateForm(formId, formProviderInfo); + default: + APP_LOGW("%{public}s warning, onAcquired type: %{public}d", __func__, type); + } + return ERR_APPEXECFWK_FORM_INVALID_PARAM; +} + +/** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnEventHandle(const Want &want) +{ + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + std::string supplyInfo = want.GetStringParam(Constants::FORM_SUPPLY_INFO); + APP_LOGD("%{public}s come: %{public}ld, %{public}s", __func__, connectId, supplyInfo.c_str()); + RemoveConnection(connectId); + return ERR_OK; +} +/** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ +void FormSupplyCallback::AddConnection(sptr connection) +{ + std::lock_guard lock_l(conMutex_); + long connectKey = FormUtil::GetCurrentMillisecond(); + while (connections_.find(connectKey) != connections_.end()) { + connectKey++; + } + connection->SetConnectId(connectKey); + connections_.emplace(connectKey, connection); +} + +/** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ +void FormSupplyCallback::RemoveConnection(long connectId) +{ + std::lock_guard lock_l(conMutex_); + auto conIterator = connections_.find(connectId); + if (conIterator != connections_.end()) { + sptr connection = conIterator->second; + if (connection != nullptr) { + FormAmsHelper::GetInstance().DisConnectServiceAbility(connection); + } + connections_.erase(connectId); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_sys_event_receiver.cpp b/services/formmgr/src/form_sys_event_receiver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1181cb65a53bebd874f56f27b1851538adab18e --- /dev/null +++ b/services/formmgr/src/form_sys_event_receiver.cpp @@ -0,0 +1,490 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "bundle_info.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "form_bms_helper.h" +#include "form_cache_mgr.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_db_info.h" +#include "form_provider_mgr.h" +#include "form_timer_mgr.h" +#include "form_util.h" +#include "form_sys_event_receiver.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string KEY_UID = "uid"; +const std::string KEY_BUNDLE_NAME = "bundleName"; +/** + * @brief Receiver Constructor. + * @param subscriberInfo Subscriber info. + */ +FormSysEventReceiver::FormSysEventReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo) + : EventFwk::CommonEventSubscriber(subscriberInfo) +{} +/** + * @brief Receive common event. + * @param eventData Common event data. + */ +void FormSysEventReceiver::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + AAFwk::Want want = eventData.GetWant(); + std::string action = want.GetAction(); + std::string bundleName = want.GetStringParam(KEY_BUNDLE_NAME); + + if (action.empty() || bundleName.empty()) { + APP_LOGE("%{public}s failed, invalid param, action: %{public}s, bundleName: %{public}s", __func__, + action.c_str(), bundleName.c_str()); + return; + } + APP_LOGI("%{public}s, action:%{public}s.", __func__, action.c_str()); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_REMOVED) { + APP_LOGI("%{public}s, bundle removed, bundleName: %{public}s", __func__, bundleName.c_str()); + HandleProviderRemoved(bundleName); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED) { + APP_LOGI("%{public}s, bundle updated, bundleName: %{public}s", __func__, bundleName.c_str()); + HandleProviderUpdated(bundleName); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { + int uid = want.GetIntParam(KEY_UID, 0); + HandleBundleDataCleared(bundleName, uid); + } else { + APP_LOGW("%{public}s warnning, invalid action.", __func__); + } +} +/** + * @brief Handle provider updated event. + * @param bundleName bundle name. + * @param uid uid. + */ +void FormSysEventReceiver::HandleProviderUpdated(const std::string &bundleName) +{ + std::vector formInfos; + bool bResult = FormDataMgr::GetInstance().GetFormRecord(bundleName, formInfos); + if (!bResult) { + APP_LOGI("%{public}s, no form info.", __func__); + return; + } + + sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); + if (iBundleMgr == nullptr) { + // GetBundleMgr() has error log + return; + } + + std::vector targetForms; + if (!iBundleMgr->GetFormsInfoByApp(bundleName, targetForms)) { + APP_LOGE("%{public}s error, failed to get forms info.", __func__); + return; + } + + if (targetForms.empty()) { + APP_LOGE("%{public}s error, targetForms is empty.", __func__); + return; + } + + std::vector removedForms; + std::vector updatedForms; + + for (FormRecord& formRecord : formInfos) { + APP_LOGI("%{public}s, provider update, formName:%{public}s", __func__, formRecord.formName.c_str()); + int64_t formId = formRecord.formId; + if (ProviderFormUpdated(formId, formRecord, targetForms)) { + updatedForms.emplace_back(formId); + continue; + } + + APP_LOGI("%{public}s, no such form anymore, delete it:%{public}s", __func__, formRecord.formName.c_str()); + if (!formRecord.formTempFlg) { + FormDbCache::GetInstance().DeleteFormInfo(formId); + } else { + FormDataMgr::GetInstance().DeleteTempForm(formId); + } + removedForms.emplace_back(formId); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + } + + if (!removedForms.empty()) { + APP_LOGI("%{public}s, clean removed forms", __func__); + FormDataMgr::GetInstance().CleanHostRemovedForms(removedForms); + } + + APP_LOGI("%{public}s, remove form timer", __func__); + for (const int64_t id : removedForms) { + FormTimerMgr::GetInstance().RemoveFormTimer(id); + } + + APP_LOGI("%{public}s, refresh form", __func__); + Want want; + for (const int64_t id : updatedForms) { + FormProviderMgr::GetInstance().RefreshForm(id, want); + } +} + +void FormSysEventReceiver::HandleProviderRemoved(const std::string &bundleName) +{ + APP_LOGI("GET into HandleProviderRemoved with bundleName : %{public}s", bundleName.c_str()); + // clean removed form in DB + std::set removedForms; + { + std::vector removedDBForm; + FormDbCache::GetInstance().DeleteFormInfoByBundleName(bundleName, removedDBForm); + for (const auto &dbForm : removedDBForm) { + removedForms.emplace(dbForm.formId); + int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(dbForm.bundleName, dbForm.moduleName); + if (matchCount == 0) { + FormBmsHelper::GetInstance().NotifyModuleRemovable(dbForm.bundleName, dbForm.moduleName); + } + } + } + // clean removed form in FormRecords + FormDataMgr::GetInstance().CleanRemovedFormRecords(bundleName, removedForms); + // clean removed temp form in FormRecords + FormDataMgr::GetInstance().CleanRemovedTempFormRecords(bundleName, removedForms); + // clean removed forms in FormHostRecords + std::vector vRemovedForms; + vRemovedForms.assign(removedForms.begin(), removedForms.end()); + FormDataMgr::GetInstance().CleanHostRemovedForms(vRemovedForms); + + // clean removed form timers + for (auto &formId : removedForms) { + FormTimerMgr::GetInstance().RemoveFormTimer(formId); + } +} + +bool FormSysEventReceiver::ProviderFormUpdated(const int64_t formId, const FormRecord &formRecord, +const std::vector &targetForms) +{ + APP_LOGI("%{public}s start", __func__); + if (targetForms.empty()) { + APP_LOGE("%{public}s error, targetForms is empty", __func__); + return false; + } + + FormInfo updatedForm; + bool bGetForm = FormDataMgr::GetInstance().GetUpdatedForm(formRecord, targetForms, updatedForm); + if (bGetForm) { + APP_LOGI("%{public}s, form is still exist,form:%{public}s", __func__, formRecord.formName.c_str()); + // update resource + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + FormCacheMgr::GetInstance().DeleteData(formId); + + FormBmsHelper::GetInstance().NotifyModuleNotRemovable(formRecord.bundleName, formRecord.moduleName); + FormTimerCfg timerCfg; + GetTimerCfg(updatedForm.updateEnabled, updatedForm.updateDuration, + updatedForm.scheduledUpateTime, timerCfg); + HandleTimerUpdate(formId, formRecord, timerCfg); + FormDataMgr::GetInstance().SetVersionUpgrade(formId, true); + return true; + } + APP_LOGI("%{public}s, no updated form.", __func__); + return false; +} +void FormSysEventReceiver::HandleBundleDataCleared(const std::string &bundleName, const int uid) +{ + APP_LOGD("%{public}s, bundleName:%{public}s, uid:%{public}d", __func__, bundleName.c_str(), uid); + // as provider data is cleared + std::set reCreateForms; + FormDataMgr::GetInstance().GetReCreateFormRecordsByBundleName(bundleName, reCreateForms); + if (reCreateForms.empty()) { + return; + } + for (int64_t formId : reCreateForms) { + ReCreateForm(formId); + } + + // as form host data is cleared + HandleFormHostDataCleared(uid); +} +void FormSysEventReceiver::HandleFormHostDataCleared(const int uid) +{ + APP_LOGD("%{public}s, uid:%{public}d", __func__, uid); + std::map removedFormsMap; + // clear formDBRecord + ClearFormDBRecordData(uid, removedFormsMap); + + // clear temp form + ClearTempFormRecordData(uid, removedFormsMap); + + // clear host data + FormDataMgr::GetInstance().ClearHostDataByUId(uid); + + // delete forms timer + for (const auto &removedForm : removedFormsMap) { + if (removedForm.second) { + FormTimerMgr::GetInstance().RemoveFormTimer(removedForm.first); + } + } +} +void FormSysEventReceiver::ClearFormDBRecordData(const int uid, std::map &removedFormsMap) +{ + std::map foundFormsMap; + std::map> noHostFormDbMap; + FormDbCache::GetInstance().GetNoHostDBForms(uid, noHostFormDbMap, foundFormsMap); + if (foundFormsMap.size() > 0) { + for (const auto &element : foundFormsMap) { + FormDataMgr::GetInstance().DeleteFormUserUid(element.first, uid); + } + } + + APP_LOGD("%{public}s, noHostFormDbMap size:%{public}d", __func__, noHostFormDbMap.size()); + if (noHostFormDbMap.size() > 0) { + BatchDeleteNoHostDBForms(uid, noHostFormDbMap, foundFormsMap); + } + + if (!foundFormsMap.empty()) { + removedFormsMap.insert(foundFormsMap.begin(), foundFormsMap.end()); + } +} +void FormSysEventReceiver::ClearTempFormRecordData(const int uid, std::map &removedFormsMap) +{ + std::map foundFormsMap; + std::map> noHostTempFormsMap; + FormDataMgr::GetInstance().GetNoHostTempForms(uid, noHostTempFormsMap, foundFormsMap); + APP_LOGD("%{public}s, noHostTempFormsMap size:%{public}d", __func__, noHostTempFormsMap.size()); + if (noHostTempFormsMap.size() > 0) { + BatchDeleteNoHostTempForms(uid, noHostTempFormsMap, foundFormsMap); + } + if (!foundFormsMap.empty()) { + removedFormsMap.insert(foundFormsMap.begin(), foundFormsMap.end()); + } +} +void FormSysEventReceiver::BatchDeleteNoHostDBForms(const int uid, std::map> &noHostFormDbMap, std::map &removedFormsMap) +{ + std::set removableModuleSet; + for (const auto &element: noHostFormDbMap) { + std::set formIds = element.second; + FormIdKey formIdKey = element.first; + std::string bundleName = formIdKey.bundleName; + std::string abilityName = formIdKey.abilityName; + int result = FormProviderMgr::GetInstance().NotifyProviderFormsBatchDelete(bundleName, abilityName, formIds); + if (result != ERR_OK) { + APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s, abilityName:%{public}s", + __func__, bundleName.c_str(), abilityName.c_str()); + for (int64_t formId : formIds) { + FormDBInfo dbInfo; + int errCode = FormDbCache::GetInstance().GetDBRecord(formId, dbInfo); + if (errCode == ERR_OK) { + dbInfo.formUserUids.emplace_back(uid); + FormDbCache::GetInstance().SaveFormInfo(dbInfo); + } + } + } else { + for (const int64_t formId : formIds) { + removedFormsMap.emplace(formId, true); + FormDBInfo dbInfo; + int errCode = FormDbCache::GetInstance().GetDBRecord(formId, dbInfo); + if (errCode == ERR_OK) { + FormIdKey removableModuleFormIdKey; + removableModuleFormIdKey.bundleName = dbInfo.bundleName; + removableModuleFormIdKey.moduleName = dbInfo.moduleName; + removableModuleSet.emplace(removableModuleFormIdKey); + FormDbCache::GetInstance().DeleteFormInfo(formId); + } + FormDataMgr::GetInstance().DeleteFormRecord(formId); + } + } + } + + for (const FormIdKey &item : removableModuleSet) { + int32_t matchCount = FormDbCache::GetInstance().GetMatchCount(item.bundleName, item.moduleName); + if (matchCount == 0) { + FormBmsHelper::GetInstance().NotifyModuleRemovable(item.bundleName, item.moduleName); + } + } +} +/** + * @brief Delete no host temp forms. + * @param uid The caller uid. + * @param noHostTempFormsMap no host temp forms. + * @param foundFormsMap Form Id list. + */ +void FormSysEventReceiver::BatchDeleteNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, std::map &foundFormsMap) +{ + for (const auto &element : noHostTempFormsMap) { + std::set formIds = element.second; + FormIdKey formIdKey = element.first; + std::string bundleName = formIdKey.bundleName; + std::string abilityName = formIdKey.abilityName; + int result = FormProviderMgr::GetInstance().NotifyProviderFormsBatchDelete(bundleName, abilityName, formIds); + if (result != ERR_OK) { + APP_LOGE("%{public}s error, NotifyProviderFormsBatchDelete failed! bundleName:%{public}s, abilityName:%{public}s", + __func__, bundleName.c_str(), abilityName.c_str()); + for (int64_t formId : formIds) { + FormDataMgr::GetInstance().AddFormUserUid(formId, uid); + } + } else { + for (int64_t formId : formIds) { + foundFormsMap.emplace(formId, true); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteTempForm(formId); + } + } + } +} +void FormSysEventReceiver::ReCreateForm(const int64_t formId) +{ + APP_LOGI("%{public}s start, formId:%{public}lld", __func__, formId); + FormRecord reCreateRecord; + FormRecord record; + bool isGetForm = FormDataMgr::GetInstance().GetFormRecord(formId, record); + if (!isGetForm) { + APP_LOGE("%{public}s error, not exist such form:%{public}lld", __func__, formId); + return; + } + FormCacheMgr::GetInstance().DeleteData(formId); + + reCreateRecord.bundleName = record.bundleName; + reCreateRecord.abilityName = record.abilityName; + reCreateRecord.formName = record.formName; + reCreateRecord.specification = record.specification; + reCreateRecord.formTempFlg = record.formTempFlg; + reCreateRecord.isInited = record.isInited; + reCreateRecord.versionUpgrade = record.versionUpgrade; + + Want want; + FormUtil::CreateFormWant(reCreateRecord.formName, reCreateRecord.specification, reCreateRecord.formTempFlg, want); + want.SetParam(Constants::RECREATE_FORM_KEY, true); + FormProviderMgr::GetInstance().ConnectAmsForRefresh(formId, reCreateRecord, want, false); +} +void FormSysEventReceiver::GetTimerCfg(const bool updateEnabled, const int updateDuration, +const std::string &configUpdateAt, FormTimerCfg& cfg) +{ + APP_LOGI("%{public}s start", __func__); + if (!updateEnabled) { + APP_LOGI("%{public}s, update disable", __func__); + return; + } + + if (updateDuration > 0) { + // interval timer + APP_LOGI("%{public}s,interval timer updateDuration:%{public}d", __func__, updateDuration); + if (updateDuration <= Constants::MIN_CONFIG_DURATION) { + cfg.updateDuration = Constants::MIN_PERIOD; + } else if (updateDuration >= Constants::MAX_CONFIG_DURATION) { + cfg.updateDuration = Constants::MAX_PERIOD; + } else { + cfg.updateDuration = updateDuration * Constants::TIME_CONVERSION; + } + cfg.enableUpdate = true; + return; + } else { + // updateAtTimer + if (configUpdateAt.empty()) { + APP_LOGI("%{public}s, configUpdateAt is empty", __func__); + return; + } + APP_LOGI("%{public}s,update at timer updateAt:%{public}s", __func__, configUpdateAt.c_str()); + + std::vector temp = FormUtil::StringSplit(configUpdateAt, Constants::TIME_DELIMETER); + if (temp.size() != Constants::UPDATE_AT_CONFIG_COUNT) { + APP_LOGE("%{public}s, invalid config", __func__); + return; + } + int hour = -1; + int min = -1; + try { + hour = std::stoi(temp[0]); + min = std::stoi(temp[1]); + } catch (const std::exception& e) { + APP_LOGE("%{public}s, failed to stoi.", __func__); + return; + } + + if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min > + Constants::MAX_MININUTE) { + APP_LOGE("%{public}s, time is invalid", __func__); + return; + } + + cfg.updateAtHour = hour; + cfg.updateAtMin = min; + cfg.enableUpdate = true; + return; + } +} + +void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, const FormRecord &record, +const FormTimerCfg &timerCfg) +{ + // both disable + if (!record.isEnableUpdate && !timerCfg.enableUpdate) { + return; + } + + // enable to disable + if (record.isEnableUpdate && !timerCfg.enableUpdate) { + FormDataMgr::GetInstance().SetEnableUpdate(formId, false); + FormTimerMgr::GetInstance().RemoveFormTimer(formId); + return; + } + + // disable to enable + if (!record.isEnableUpdate && timerCfg.enableUpdate) { + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, timerCfg.updateDuration, timerCfg.updateAtHour, + timerCfg.updateAtMin); + if (timerCfg.updateDuration > 0) { + APP_LOGI("%{public}s, add interval timer:%{public}lld", __func__, timerCfg.updateDuration); + FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateDuration); + } else { + APP_LOGI("%{public}s, add at timer:%{public}d, %{public}d", __func__, timerCfg.updateAtHour, + timerCfg.updateAtMin); + FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateAtHour, timerCfg.updateAtMin); + } + + return; + } + + // both enable + UpdateType type; + if (record.updateDuration > 0) { + if (timerCfg.updateDuration > 0) { + // no change + if (record.updateDuration == timerCfg.updateDuration) { + return; + } + // interval change + type = TYPE_INTERVAL_CHANGE; + } else { + // interval to updateat + type = TYPE_INTERVAL_TO_ATTIME; + } + } else { + if (timerCfg.updateDuration > 0) { + // updateat to interval + type = TYPE_ATTIME_TO_INTERVAL; + } else { + // no change; + if (record.updateAtHour == timerCfg.updateAtHour && record.updateAtMin == timerCfg.updateAtMin) { + return; + } + // updateat change + type = TYPE_ATTIME_CHANGE; + } + } + + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, timerCfg.updateDuration, timerCfg.updateAtHour, + timerCfg.updateAtMin); + FormTimerMgr::GetInstance().UpdateFormTimer(formId, type, timerCfg); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_task_mgr.cpp b/services/formmgr/src/form_task_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83fe1cd8bab5abc283f1f01268a02cd6ba5e0395 --- /dev/null +++ b/services/formmgr/src/form_task_mgr.cpp @@ -0,0 +1,566 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_constants.h" +#include "form_data_mgr.h" +#include "form_host_interface.h" +#include "form_item_info.h" +#include "form_provider_interface.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" + +namespace OHOS { +namespace AppExecFwk { +FormTaskMgr::FormTaskMgr() {} +FormTaskMgr::~FormTaskMgr() {} +/** + * @brief Acquire form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostAcquireTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function acquireProviderFormInfoFunc = std::bind( + &FormTaskMgr::AcquireProviderFormInfo, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(acquireProviderFormInfoFunc); +} +/** + * @brief Delete form data from form provider(task). + * @param formId The Id of the form. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostDeleteTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function notifyFormDeleteFunc = std::bind ( + &FormTaskMgr::NotifyFormDelete, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(notifyFormDeleteFunc); +} + +/** + * @brief Refresh form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::PostRefreshTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function notifyFormUpdateFunc = std::bind ( + &FormTaskMgr::NotifyFormUpdate, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(notifyFormUpdateFunc); +} + +/** + * @brief Cast temp form data from form provider(task). + * + * @param formId The Id of the form. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::PostCastTempTask(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function notifyCastTempFunc = std::bind ( + &FormTaskMgr::NotifyCastTemp, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(notifyCastTempFunc); +} + +/** + * @brief Post form data to form host(task) when acquire form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::PostAcquireTaskToHost(const int64_t formId, const FormRecord &record, +const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function acquireTaskToHostFunc = std::bind ( + &FormTaskMgr::AcquireTaskToHost, + this, + formId, + record, + remoteObject); + eventHandler_->PostTask(acquireTaskToHostFunc); +} + +/** + * @brief Post form data to form host(task) when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::PostUpdateTaskToHost(const int64_t formId, const FormRecord &record, +const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + + APP_LOGD("%{public}s, post the task of updateTaskToHostFunc.", __func__); + std::function updateTaskToHostFunc = std::bind ( + &FormTaskMgr::UpdateTaskToHost, + this, + formId, + record, + remoteObject); + eventHandler_->PostTask(updateTaskToHostFunc); +} + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the form. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +/** + * @brief Handel form host died(task). + * @param remoteHost Form host proxy object. + */ +void FormTaskMgr::PostHostDiedTask(const sptr &remoteHost) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return; + } + std::function postTaskFunc = std::bind ( + &FormTaskMgr::HostDied, + this, + remoteHost); + eventHandler_->PostTask(postTaskFunc); +} + +/** + * @brief Post event notify to form provider. + * + * @param formEvent The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ +void FormTaskMgr::PostEventNotifyTask(const std::vector &formEvent, const int32_t formVisibleType, +const Want &want, const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function eventNotifyFunc = std::bind ( + &FormTaskMgr::EventNotify, + this, + formEvent, + formVisibleType, + want, + remoteObject); + eventHandler_->PostTask(eventNotifyFunc); +} +/** + * @brief Post provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostProviderBatchDeleteTask(std::set &formIds, const Want &want, +const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function batchDeleteFunc = std::bind ( + &FormTaskMgr::ProviderBatchDelete, + this, + formIds, + want, + remoteObject); + eventHandler_->PostTask(batchDeleteFunc); +} +/** + * @brief Post message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostFormEventTask(const int64_t formId, const std::string &message, const Want &want, +const sptr &remoteObject) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function formEventFunc = std::bind ( + &FormTaskMgr::FireFormEvent, + this, + formId, + message, + want, + remoteObject); + eventHandler_->PostTask(formEventFunc); +} + +/** + * @brief Post uninstall message to form host(task). + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::PostUninstallTaskToHost(const std::vector &formIds, const sptr &remoteObject) +{ + APP_LOGI("%{public}s start", __func__); + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); + return; + } + std::function uninstallFunc = std::bind ( + &FormTaskMgr::FormUninstall, + this, + formIds, + remoteObject); + eventHandler_->PostTask(uninstallFunc); + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Acquire form data from form provider. + * @param formId The Id of the from. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::AcquireProviderFormInfo(const int64_t formId, const Want &want, +const sptr &remoteObject) +{ + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + int error = formProviderProxy->AcquireProviderFormInfo(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} + +/** + * @brief Notify form provider for delete form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} + +/** + * @brief Notify form provider for updating form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::NotifyFormUpdate(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->NotifyFormUpdate(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to notify form update.", __func__); + } +} + +/** + * @brief Event notify to form provider. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want The want of the form. + * @param remoteObject The form provider proxy object. + * @return none. + */ +void FormTaskMgr::EventNotify(const std::vector &formEvents, const int32_t formVisibleType, const Want &want, +const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->EventNotify(formEvents, formVisibleType, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to send event notify.", __func__); + } +} + +/** + * @brief Notify form provider for cast temp form. + * + * @param formId The Id of the from. + * @param want The want of the form. + * @param remoteObject Form provider proxy object. + * @return none. + */ +void FormTaskMgr::NotifyCastTemp(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->NotifyFormCastTempForm(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } +} + +/** + * @brief Post form data to form host when acquire form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::AcquireTaskToHost(const int64_t formId, const FormRecord &record, +const sptr &remoteObject) +{ + APP_LOGI("FormTaskMgr AcquireTaskToHost, formId:%{public}lld", formId); + + sptr remoteFormHost = iface_cast(remoteObject); + if (remoteFormHost == nullptr) { + APP_LOGE("%{public}s fail, Failed to get form host proxy", __func__); + return; + } + + APP_LOGD("FormTaskMgr remoteFormHost OnAcquired"); + remoteFormHost->OnAcquired(CreateFormJsInfo(formId, record)); +} + +/** + * @brief Post form data to form host when update form. + * @param formId The Id of the form. + * @param callingUid Calling uid. + * @param info Form configure info. + * @param wantParams WantParams of the request. + * @param remoteObject Form provider proxx object. + */ +void FormTaskMgr::UpdateTaskToHost(const int64_t formId, const FormRecord &record, +const sptr &remoteObject) +{ + APP_LOGI("%{public}s start.", __func__); + + sptr remoteFormHost = iface_cast(remoteObject); + if (remoteFormHost == nullptr) { + APP_LOGE("%{public}s fail, Failed to get form host proxy.", __func__); + return; + } + + APP_LOGD("%{public}s, FormTaskMgr remoteFormHost OnUpdate.", __func__); + remoteFormHost->OnUpdate(CreateFormJsInfo(formId, record)); + + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Handle form host died. + * @param remoteHost Form host proxy object. + */ +void FormTaskMgr::HostDied(const sptr &remoteHost) +{ + APP_LOGI("%{public}s, remote client died event", __func__); + if (remoteHost == nullptr) { + APP_LOGI("%{public}s, remote client died, invalid param", __func__); + return; + } + FormDataMgr::GetInstance().HandleHostDied(remoteHost); +} +/** + * @brief Post provider batch delete. + * @param formIds The Id list. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::ProviderBatchDelete(std::set &formIds, const Want &want, +const sptr &remoteObject) +{ + APP_LOGI("%{public}s called.", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + std::vector vFormIds; + vFormIds.assign(formIds.begin(), formIds.end()); + int error = formProviderProxy->NotifyFormsDelete(vFormIds, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s failed", __func__); + } +} +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &remoteObject) +{ + APP_LOGI("%{public}s start", __func__); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s, Failed to get formProviderProxy", __func__); + return; + } + + int error = formProviderProxy->FireFormEvent(formId, message, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s, Failed to fire message event to form provider", __func__); + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Handle uninstall message. + * @param formIds The Id list of the forms. + * @param remoteObject Form provider proxy object. + */ +void FormTaskMgr::FormUninstall(const std::vector &formIds, + const sptr &remoteObject) +{ + APP_LOGI("%{public}s start", __func__); + sptr remoteFormHost = iface_cast(remoteObject); + if (remoteFormHost == nullptr) { + APP_LOGE("%{public}s fail, Failed to get form host proxy.", __func__); + return; + } + + remoteFormHost->OnUninstall(formIds); + + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Create form data for form host. + * @param formId The Id of the form. + * @param record Form record. + * @return Form data. + */ +FormJsInfo FormTaskMgr::CreateFormJsInfo(const int64_t formId, const FormRecord &record) +{ + FormJsInfo form; + form.formId = formId; + form.bundleName = record.bundleName; + form.abilityName = record.abilityName; + form.formName = record.formName; + form.formTempFlg = record.formTempFlg; + form.jsFormCodePath = record.jsFormCodePath; + form.formData = record.formProviderInfo.GetFormDataString(); + + return form; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_timer_mgr.cpp b/services/formmgr/src/form_timer_mgr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a48df9d76830a42e07fdb045e03054b0412a7498 --- /dev/null +++ b/services/formmgr/src/form_timer_mgr.cpp @@ -0,0 +1,1017 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "form_constants.h" +#include "form_provider_mgr.h" +#include "form_refresh_limiter.h" +#include "form_timer_mgr.h" +#include "form_util.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormTimerMgr::FormTimerMgr() +{ + Init(); +} +FormTimerMgr::~FormTimerMgr() +{ + ClearIntervalTimer(); +} +/** + * @brief Add form timer by timer task. + * @param task The form timer task. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddFormTimer(const FormTimer &task) +{ + APP_LOGI("%{public}s, formId: %{public}lld", __func__, task.formId); + if (task.isUpdateAt) { + if (task.hour >= Constants::MIN_TIME && task.hour <= Constants::MAX_HOUR && task.min >= Constants::MIN_TIME && + task.min <= Constants::MAX_MININUTE) { + return AddUpdateAtTimer(task); + } else { + APP_LOGE("%{public}s failed, update at time is invalid", __func__); + return false; + } + } else { + if (task.period >= Constants::MIN_PERIOD && task.period <= Constants::MAX_PERIOD && + (task.period % Constants::MIN_PERIOD) == 0) { + return AddIntervalTimer(task); + } else { + APP_LOGE("%{public}s failed, interval time is invalid", __func__); + return false; + } + } +} +/** + * @brief Add duration form timer. + * @param formId The Id of the form. + * @param updateDuration Update duration + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddFormTimer(const int64_t formId, const long updateDuration) +{ + FormTimer timerTask(formId, updateDuration); + return AddFormTimer(timerTask); +} +/** + * @brief Add scheduled form timer. + * @param formId The Id of the form. + * @param updateAtHour Hour + * @param updateAtMin Min + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddFormTimer(const int64_t formId, const long updateAtHour, const long updateAtMin) +{ + FormTimer timerTask(formId, updateAtHour, updateAtMin); + return AddFormTimer(timerTask); +} +/** + * @brief Remove form timer by form id. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::RemoveFormTimer(const int64_t formId) +{ + APP_LOGI("%{public}s, task: %{public}lld", __func__, formId); + + if (!DeleteIntervalTimer(formId)) { + DeleteUpdateAtTimer(formId); + } + + DeleteDynamicItem(formId); + refreshLimiter_.DeleteItem(formId); + + return true; +} +/** + * @brief Update form timer. + * @param formId The Id of the form. + * @param type Timer type. + * @param timerCfg Timer config. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateFormTimer(const int64_t formId, const UpdateType &type, const FormTimerCfg &timerCfg) +{ + if (!timerCfg.enableUpdate) { + APP_LOGW("%{public}s, enableUpdate is false", __func__); + return false; + } + + switch (type) { + case UpdateType::TYPE_INTERVAL_CHANGE: { + return UpdateIntervalValue(formId, timerCfg); + } + case UpdateType::TYPE_ATTIME_CHANGE: { + return UpdateAtTimerValue(formId, timerCfg); + } + case UpdateType::TYPE_INTERVAL_TO_ATTIME: { + return IntervalToAtTimer(formId, timerCfg); + } + case UpdateType::TYPE_ATTIME_TO_INTERVAL: { + return AtTimerToIntervalTimer(formId, timerCfg); + } + default: { + APP_LOGE("%{public}s failed, invalid UpdateType", __func__); + return false; + } + } +} +/** + * @brief Update Interval timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateIntervalValue(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateDuration < Constants::MIN_PERIOD || timerCfg.updateDuration > Constants::MAX_PERIOD + || (timerCfg.updateDuration % Constants::MIN_PERIOD) != 0) { + APP_LOGE("%{public}s failed, invalid param", __func__); + return false; + } + + std::lock_guard lock(intervalMutex_); + auto intervalTask = intervalTimerTasks_.find(formId); + if (intervalTask != intervalTimerTasks_.end()) { + intervalTask->second.period = timerCfg.updateDuration; + return true; + } else { + APP_LOGE("%{public}s failed, the interval timer is not exist", __func__); + return false; + } +} +/** + * @brief Update update at timer task value. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateAtTimerValue(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateAtHour < Constants::MIN_TIME || timerCfg.updateAtHour > Constants::MAX_HOUR + || timerCfg.updateAtMin < Constants::MIN_TIME || timerCfg.updateAtMin > Constants::MAX_MININUTE) { + APP_LOGE("%{public}s failed, time is invalid", __func__); + return false; + } + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + UpdateAtItem changedItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->refreshTask.formId == formId) { + changedItem = *itItem; + updateAtTimerTasks_.erase(itItem); + break; + } + } + + if (changedItem.refreshTask.formId == 0) { + APP_LOGE("%{public}s failed, the update at timer is not exist", __func__); + return false; + } + changedItem.refreshTask.hour = timerCfg.updateAtHour; + changedItem.refreshTask.min = timerCfg.updateAtMin; + changedItem.updateAtTime = changedItem.refreshTask.hour * Constants::MIN_PER_HOUR + changedItem.refreshTask.min; + AddUpdateAtItem(changedItem); + } + + UpdateAtTimerAlarm(); + return true; +} +/** + * @brief Interval timer task to update at timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::IntervalToAtTimer(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateAtHour < Constants::MIN_TIME || timerCfg.updateAtHour > Constants::MAX_HOUR + || timerCfg.updateAtMin < Constants::MIN_TIME || timerCfg.updateAtMin > Constants::MAX_MININUTE) { + APP_LOGE("%{public}s failed, time is invalid", __func__); + return false; + } + + std::lock_guard lock(intervalMutex_); + FormTimer timerTask; + auto intervalTask = intervalTimerTasks_.find(formId); + if (intervalTask != intervalTimerTasks_.end()) { + timerTask = intervalTask->second; + intervalTimerTasks_.erase(intervalTask); + + timerTask.isUpdateAt = true; + timerTask.hour = timerCfg.updateAtHour; + timerTask.min = timerCfg.updateAtMin; + if (!AddUpdateAtTimer(timerTask)) { + APP_LOGE("%{public}s, failed to add update at timer", __func__); + return false; + } + return true; + } else { + APP_LOGE("%{public}s failed, the interval timer is not exist", __func__); + return false; + } +} +/** + * @brief Update at timer task to interval timer task. + * @param formId The Id of the form. + * @param timerCfg task value. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AtTimerToIntervalTimer(const int64_t formId, const FormTimerCfg &timerCfg) +{ + if (timerCfg.updateDuration < Constants::MIN_PERIOD || timerCfg.updateDuration > Constants::MAX_PERIOD + || (timerCfg.updateDuration % Constants::MIN_PERIOD) != 0) { + APP_LOGE("%{public}s failed, time is invalid", __func__); + return false; + } + + UpdateAtItem targetItem; + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->refreshTask.formId == formId) { + targetItem = *itItem; + updateAtTimerTasks_.erase(itItem); + break; + } + } + } + + UpdateAtTimerAlarm(); + + if (targetItem.refreshTask.formId == 0) { + APP_LOGE("%{public}s failed, the update at timer is not exist", __func__); + return false; + } + targetItem.refreshTask.isUpdateAt = false; + targetItem.refreshTask.period = timerCfg.updateDuration; + targetItem.refreshTask.refreshTime = LONG_MAX; + if (!AddIntervalTimer(targetItem.refreshTask)) { + APP_LOGE("%{public}s, failed to add interval timer", __func__); + return false; + } + return true; +} +/** + * @brief Is limiter enable refresh. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::IsLimiterEnableRefresh(const int64_t formId) +{ + return refreshLimiter_.IsEnableRefresh(formId); +} +/** + * @brief Increase refresh count. + * @param formId The Id of the form. + */ +void FormTimerMgr::IncreaseRefreshCount(const int64_t formId) +{ + refreshLimiter_.Increase(formId); +} +/** + * @brief Set next refresh time. + * @param formId The Id of the form. + * @param nextGapTime Next gap time. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::SetNextRefreshTime(const int64_t formId, const long nextGapTime) +{ + if (nextGapTime < Constants::MIN_NEXT_TIME) { + APP_LOGE("%{public}s failed, nextGapTime is invalid, nextGapTime:%{public}ld", __func__, nextGapTime); + return false; + } + auto timeSinceEpoch = std::chrono::steady_clock::now().time_since_epoch(); + auto timeInSec = std::chrono::duration_cast(timeSinceEpoch).count(); + int64_t refreshTime = timeInSec + nextGapTime * Constants::MS_PER_SECOND; + std::lock_guard lock(refreshMutex_); + bool isExist = false; + for (auto &refreshItem: dynamicRefreshTasks_) { + if (refreshItem.formId == formId) { + refreshItem.settedTime = refreshTime; + isExist = true; + break; + } + } + if (!isExist) { + DynamicRefreshItem theItem; + theItem.formId = formId; + theItem.settedTime = refreshTime; + dynamicRefreshTasks_.emplace_back(theItem); + } + std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to UpdateDynamicAlarm", __func__); + return false; + } + refreshLimiter_.AddItem(formId); + SetEnableFlag(formId, false); + + return true; +} + +void FormTimerMgr::SetEnableFlag(int64_t formId, bool flag) +{ + // try interval list + auto iter = intervalTimerTasks_.find(formId); + if (iter != intervalTimerTasks_.end()) { + iter->second.isEnable = flag; + APP_LOGI("%{public}s, formId:%{public}lld, isEnable:%{public}d", __func__, formId, flag ? 1 : 0); + return; + } +} + +/** + * @brief Get refresh count. + * @param formId The Id of the form. + * @return Returns refresh count. + */ +int FormTimerMgr::GetRefreshCount(const int64_t formId) const +{ + return refreshLimiter_.GetRefreshCount(formId); +} +/** + * @brief Mark remind. + * @param formId The Id of the form. + * @return true or false. + */ +void FormTimerMgr::MarkRemind(const int64_t formId) +{ + refreshLimiter_.MarkRemind(formId); +} +/** + * @brief Add update at timer. + * @param task Update time task. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddUpdateAtTimer(const FormTimer &task) +{ + APP_LOGI("%{public}s start", __func__); + { + std::lock_guard lock(updateAtMutex_); + for (auto &updateAtTimer : updateAtTimerTasks_) { + if (updateAtTimer.refreshTask.formId == task.formId) { + APP_LOGW("%{public}s, already exist formTimer, formId:%{public}lld task", __func__, task.formId); + return true; + } + } + + UpdateAtItem atItem; + atItem.refreshTask = task; + atItem.updateAtTime = task.hour * Constants::MIN_PER_HOUR + task.min; + + AddUpdateAtItem(atItem); + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update alarm.", __func__); + return false; + } + + return refreshLimiter_.AddItem(task.formId); +} +/** + * @brief Add update interval timer task. + * @param task Update interval timer task. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::AddIntervalTimer(const FormTimer &task) +{ + APP_LOGI("%{public}s start", __func__); + { + std::lock_guard lock(intervalMutex_); + EnsureInitIntervalTimer(); + if (intervalTimerTasks_.find(task.formId) != intervalTimerTasks_.end()) { + APP_LOGW("%{public}s, already exist formTimer, formId:%{public}lld task", __func__, task.formId); + return true; + } + intervalTimerTasks_.emplace(task.formId, task); + } + UpdateLimiterAlarm(); + return refreshLimiter_.AddItem(task.formId); +} +/** + * @brief Add update at timer item. + * @param task Update at timer item. + */ +void FormTimerMgr::AddUpdateAtItem(const UpdateAtItem &atItem) +{ + if (updateAtTimerTasks_.empty()) { + updateAtTimerTasks_.emplace_back(atItem); + return; + } + + UpdateAtItem firstItem = updateAtTimerTasks_.front(); + if (atItem.updateAtTime < firstItem.updateAtTime) { + updateAtTimerTasks_.emplace_front(atItem); + return; + } + + bool isInsert = false; + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (atItem.updateAtTime < itItem->updateAtTime) { + updateAtTimerTasks_.insert(itItem, atItem); + isInsert = true; + break; + } + } + + if (!isInsert) { + updateAtTimerTasks_.emplace_back(atItem); + } +} +/** + * @brief Handle system time changed. + */ +void FormTimerMgr::HandleSystemTimeChanged() +{ + APP_LOGI("%{public}s start", __func__); + if (!updateAtTimerTasks_.empty()) { + UpdateAtTimerAlarm(); + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Reset form limiter. + */ +void FormTimerMgr::HandleResetLimiter() +{ + APP_LOGI("%{public}s start", __func__); + + std::vector remindTasks; + bool bGetTasks = GetRemindTasks(remindTasks); + if (bGetTasks) { + APP_LOGI("%{public}s failed, remind when reset limiter", __func__); + for (auto &task : remindTasks) { + ExecTimerTask(task); + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Update attime trigger. + * @param updateTime Update time. + */ +void FormTimerMgr::OnUpdateAtTrigger(long updateTime) +{ + APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); + std::vector updateList; + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->updateAtTime == updateTime && itItem->refreshTask.isEnable) { + updateList.emplace_back(*itItem); + } + } + } + + UpdateAtTimerAlarm(); + + if (!updateList.empty()) { + APP_LOGI("%{public}s, update at timer triggered, trigged time: %{public}ld", __func__, updateTime); + for (auto &item : updateList) { + ExecTimerTask(item.refreshTask); + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Dynamic time trigger. + * @param updateTime Update time. + */ +void FormTimerMgr::OnDynamicTimeTrigger(long updateTime) +{ + APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); + std::vector updateList; + { + std::lock_guard lock(dynamicMutex_); + auto timeSinceEpoch = std::chrono::steady_clock::now().time_since_epoch(); + auto timeInSec = std::chrono::duration_cast(timeSinceEpoch).count(); + long markedTime = timeInSec + Constants::ABS_REFRESH_MS; + std::vector::iterator itItem; + for (itItem = dynamicRefreshTasks_.begin(); itItem != dynamicRefreshTasks_.end();) { + if (itItem->settedTime <= updateTime || itItem->settedTime <= markedTime) { + if (refreshLimiter_.IsEnableRefresh(itItem->formId)) { + FormTimer timerTask(itItem->formId, true); + updateList.emplace_back(timerTask); + } + itItem = dynamicRefreshTasks_.erase(itItem); + SetIntervalEnableFlag(itItem->formId, true); + } else { + itItem++; + } + } + std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); + } + + UpdateDynamicAlarm(); + if (!updateList.empty()) { + APP_LOGI("%{public}s triggered, trigged time: %{public}ld", __func__, updateTime); + for (auto &task : updateList) { + ExecTimerTask(task); + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Get remind tasks. + * @param remindTasks Remind tasks. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::GetRemindTasks(std::vector &remindTasks) +{ + APP_LOGI("%{public}s start", __func__); + std::vector remindList = refreshLimiter_.GetRemindListAndResetLimit(); + for (int64_t id : remindList) { + FormTimer formTimer(id, false); + remindTasks.emplace_back(formTimer); + } + + UpdateLimiterAlarm(); + + if(remindTasks.size() > 0) { + return true; + } else { + return false; + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Set enableFlag for interval timer task. + * @param formId The Id of the form. + * @param flag Enable flag. + */ +void FormTimerMgr::SetIntervalEnableFlag(int64_t formId, bool flag) +{ + std::lock_guard lock(intervalMutex_); + // try interval list + auto refreshTask = intervalTimerTasks_.find(formId); + if (refreshTask != intervalTimerTasks_.end()) { + refreshTask->second.isEnable = flag; + APP_LOGI("%{public}s, formId:%{public}lld, isEnable:%{public}d", __func__, formId, flag ? 1 : 0); + return; + } +} +/** + * @brief Delete interval timer task. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::DeleteIntervalTimer(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + bool isExist = false; + std::lock_guard lock(intervalMutex_); + auto intervalTask = intervalTimerTasks_.find(formId); + if (intervalTask != intervalTimerTasks_.end()) { + intervalTimerTasks_.erase(intervalTask); + isExist = true; + } + + if (intervalTimerTasks_.empty()) { + ClearIntervalTimer(); + } + APP_LOGI("%{public}s end", __func__); + return isExist; +} +/** + * @brief Delete update at timer. + * @param formId The Id of the form. + */ +void FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + { + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->refreshTask.formId == formId) { + updateAtTimerTasks_.erase(itItem); + break; + } + } + } + + UpdateAtTimerAlarm(); + + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Delete dynamic refresh item. + * @param formId The Id of the form. + */ +void FormTimerMgr::DeleteDynamicItem(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(dynamicMutex_); + std::vector::iterator itItem; + for (itItem = dynamicRefreshTasks_.begin(); itItem != dynamicRefreshTasks_.end();) { + if (itItem->formId == formId) { + dynamicRefreshTasks_.erase(itItem); + SetIntervalEnableFlag(itItem->formId, true); + break; + } + } + std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); + + UpdateDynamicAlarm(); + APP_LOGI("%{public}s end", __func__); +} +/** +* @brief interval timer task timeout. +*/ +void FormTimerMgr::OnIntervalTimeOut() +{ + APP_LOGI("%{public}s start", __func__); + std::lock_guard lock(intervalMutex_); + std::vector updateList; + long currentTime = FormUtil::GetCurrentNanosecond() / Constants::TIME_1000000; + for (auto &intervalPair : intervalTimerTasks_) { + FormTimer &intervalTask = intervalPair.second; + if ((intervalTask.refreshTime == LONG_MAX || (currentTime - intervalTask.refreshTime) >= intervalTask.period || + std::abs((currentTime - intervalTask.refreshTime) - intervalTask.period) < Constants::ABS_TIME) && + intervalTask.isEnable && refreshLimiter_.IsEnableRefresh(intervalTask.formId)) { + intervalTask.refreshTime = currentTime; + updateList.emplace_back(intervalTask); + } + } + + if (!updateList.empty()) { + for (auto &task : updateList) { + ExecTimerTask(task); + } + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Update at timer task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateAtTimerAlarm() +{ + APP_LOGI("%{public}s start", __func__); + // AlarmManager* alarm = GetAlarmManagerLocked(); + // if (alarm == nullptr) { + // APP_LOGE("%{public}s failed, failed to get alarm manager, can not updateAlarm", __func__); + // return false; + // } + struct tm tmAtTime = {0}; + auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + struct tm* ptm = localtime_r(&tt, &tmAtTime); + if (ptm == nullptr) { + APP_LOGE("%{public}s failed, localtime error", __func__); + return false; + } + + int nowAtTime = tmAtTime.tm_hour * Constants::MIN_PER_HOUR + tmAtTime.tm_min; + long currentTime = FormUtil::GetCurrentMillisecond(); + UpdateAtItem findedItem; + bool bFinded = FindNextAtTimerItem(nowAtTime, findedItem); + if (!bFinded) { + ClearUpdateAtTimerResource(); + APP_LOGI("%{public}s, no update at task in system now.", __func__); + return true; + } + + int nextWakeUpTime = findedItem.updateAtTime; + tmAtTime.tm_sec = 0; + tmAtTime.tm_hour = findedItem.refreshTask.hour; + tmAtTime.tm_min = findedItem.refreshTask.min; + long selectTime = FormUtil::GetMillisecondFromTm(tmAtTime); + if (selectTime < currentTime) { + tmAtTime.tm_mday += 1; + nextWakeUpTime += (Constants::HOUR_PER_DAY * Constants::MIN_PER_HOUR); + } + + if (nextWakeUpTime == atTimerWakeUpTime_) { + APP_LOGW("%{public}s end, wakeUpTime not change, no need update alarm.", __func__); + return true; + } + + // PendingIntent pendingIntent = getPendingIntent(findedItem.updateAtTime); + // if (pendingIntent == null) { + // HiLog.error(LABEL_LOG, "create pendingIntent failed."); + // return false; + // } + atTimerWakeUpTime_ = nextWakeUpTime; + // if (currentPendingIntent != null) { + // alarm.cancel(currentPendingIntent); + // } + // currentPendingIntent = pendingIntent; + // alarm.setExact(AlarmManager.RTC_WAKEUP, FormUtil::GetMillisecondFromTm(tmAtTime), pendingIntent); + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Update limiter task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateLimiterAlarm() +{ + APP_LOGI("%{public}s start", __func__); + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // HiLog.error(LABEL_LOG, "faied to get alarm manager, can not updateLimiterAlarm"); + // return false; + // } + + // PendingIntent pendingIntent = getLimiterPendingIntent(); + // if (pendingIntent == null) { + // HiLog.error(LABEL_LOG, "create limiterPendingIntent failed."); + // return false; + // } + + // if (limiterPendingIntent != null) { + // alarm.cancel(limiterPendingIntent); + // } + // limiterPendingIntent = pendingIntent; + + // Calendar calendar = Calendar.getInstance(); + // calendar.set(Calendar.DATE, Calendar.getInstance().get(Calendar.DATE)); + // calendar.set(Calendar.HOUR_OF_DAY, MAX_HOUR); + // calendar.set(Calendar.MINUTE, MAX_MININUTE); + // calendar.set(Calendar.SECOND, MAX_SECOND); + // calendar.set(Calendar.MILLISECOND, LIMIT_MS); + // alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Update dynamic refresh task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateDynamicAlarm() +{ + APP_LOGI("%{public}s start", __func__); + if (dynamicRefreshTasks_.empty()) { + ClearDynamicResource(); + return true; + } + + bool needUpdate = false; + DynamicRefreshItem firstTask = dynamicRefreshTasks_.at(0); + if (dynamicWakeUpTime_ != firstTask.settedTime) { + dynamicWakeUpTime_ = firstTask.settedTime; + needUpdate = true; + } + + if (!needUpdate) { + APP_LOGE("%{public}s failed, no need to UpdateDynamicAlarm.", __func__); + return true; + } + + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // HiLog.error(LABEL_LOG, "faied to get alarm manager, can not UpdateDynamicAlarm."); + // return false; + // } + + // PendingIntent pendingIntent = getDynamicPendingIntent(dynamicWakeUpTime); + // if (pendingIntent == null) { + // HiLog.error(LABEL_LOG, "create dynamic pendingIntent failed.", __func__); + // return false; + // } + // if (dynamicPendingIntent != null) { + // alarm.cancel(dynamicPendingIntent); + // } + // dynamicPendingIntent = pendingIntent; + // alarm.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, dynamicWakeUpTime, pendingIntent); + APP_LOGI("%{public}s end", __func__); + + return true; +} +/** + * @brief Clear dynamic refresh resource. + */ +void FormTimerMgr::ClearDynamicResource() +{ + APP_LOGI("%{public}s start", __func__); + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // return; + // } + + // if (dynamicPendingIntent != null) { + // alarm.cancel(dynamicPendingIntent); + // dynamicPendingIntent = null; + // } + dynamicWakeUpTime_ = LONG_MAX; + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Fint next at timer item. + * @param nowTime Update time. + * @param updateAtItem Next at timer item. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::FindNextAtTimerItem(const int nowTime, UpdateAtItem &updateAtItem) +{ + APP_LOGI("%{public}s start", __func__); + if (updateAtTimerTasks_.empty()) { + APP_LOGW("%{public}s, updateAtTimerTasks_ is empty", __func__); + return false; + } + + std::lock_guard lock(updateAtMutex_); + std::list::iterator itItem; + for (itItem = updateAtTimerTasks_.begin(); itItem != updateAtTimerTasks_.end(); itItem++) { + if (itItem->updateAtTime > nowTime) { + updateAtItem = *itItem; + break; + } + } + + if (itItem == updateAtTimerTasks_.end()) { + updateAtItem = updateAtTimerTasks_.front(); + } + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Clear update at timer resource. + */ +void FormTimerMgr::ClearUpdateAtTimerResource() +{ + APP_LOGI("%{public}s start", __func__); + if (!updateAtTimerTasks_.empty()) { + APP_LOGW("%{public}s, updateAtTimerTasks_ is not empty", __func__); + return; + } + + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // return; + // } + + // if (currentPendingIntent != null) { + // alarm.cancel(currentPendingIntent); + // currentPendingIntent = null; + // } + atTimerWakeUpTime_ = LONG_MAX; + + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Ensure init interval timer resource. + */ +void FormTimerMgr::EnsureInitIntervalTimer() +{ + if (intervalTimer_ != NULL) { + return; + } + + APP_LOGI("%{public}s, init base timer task", __func__); + intervalTimer_ = new Utils::Timer("interval timer"); + uint32_t iResult = intervalTimer_->Setup(); + if (iResult != ERR_OK) { + APP_LOGE("%{public}s failed, init base timer task error", __func__); + return; + } + auto timeCallback = std::bind(&FormTimerMgr::OnIntervalTimeOut, this); + intervalTimer_->Register(timeCallback, Constants::MIN_PERIOD); + + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Clear interval timer resource. + */ +void FormTimerMgr::ClearIntervalTimer() +{ + APP_LOGI("%{public}s start", __func__); + if (intervalTimer_ != nullptr) { + APP_LOGI("%{public}s clear interval timer start", __func__); + intervalTimer_->Shutdown(); + delete intervalTimer_; + intervalTimer_ = nullptr; + APP_LOGI("%{public}s clear interval timer end", __func__); + } + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Get thread pool for timer task. + */ +OHOS::ThreadPool* FormTimerMgr::GetTaskThreadExecutor() +{ + APP_LOGI("%{public}s start", __func__); + if (taskExecutor_ == nullptr) { + taskExecutor_ = new OHOS::ThreadPool("timer task thread"); + taskExecutor_->Start(Constants::WORK_POOL_SIZE); + } + APP_LOGI("%{public}s end", __func__); + return taskExecutor_; +} + +/** + * @brief Execute Form timer task. + * @param timerTask Form timer task. + */ +void FormTimerMgr::ExecTimerTask(const FormTimer &timerTask) +{ + APP_LOGI("%{public}s start", __func__); + OHOS::ThreadPool* Executor = GetTaskThreadExecutor(); + if (Executor != nullptr) { + APP_LOGI("%{public}s run", __func__); + AAFwk::Want want; + if (timerTask.isCountTimer) { + want.SetParam(Constants::KEY_IS_TIMER, true); + } + auto task = std::bind(&FormProviderMgr::RefreshForm, &FormProviderMgr::GetInstance(), timerTask.formId, want); + Executor->AddTask(task); + } + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Init. + */ +void FormTimerMgr::Init() +{ + APP_LOGI("%{public}s start", __func__); + timerReceiver_ = nullptr; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(Constants::ACTION_UPDATEATTIMER); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); + + // init TimerReceiver + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + // subscribeInfo.SetPermission(permissin); + timerReceiver_ = std::make_shared(subscribeInfo); + EventFwk::CommonEventManager::SubscribeCommonEvent(timerReceiver_); + + intervalTimer_ = nullptr; + taskExecutor_ = nullptr; + + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Receiver Constructor. + * @param subscriberInfo Subscriber info. + */ +FormTimerMgr::TimerReceiver::TimerReceiver(const EventFwk::CommonEventSubscribeInfo &subscriberInfo) + : EventFwk::CommonEventSubscriber(subscriberInfo) +{} +/** + * @brief Receive common event. + * @param eventData Common event data. + */ +void FormTimerMgr::TimerReceiver::OnReceiveEvent(const EventFwk::CommonEventData &eventData) +{ + AAFwk::Want want = eventData.GetWant(); + std::string action = want.GetAction(); + + APP_LOGI("%{public}s, action:%{public}s.", __func__, action.c_str()); + + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED + || action == EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) { + FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + } else if (action == Constants::ACTION_UPDATEATTIMER) { + int type = want.GetIntParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_STATIC_UPDATE); + if (type == Constants::TYPE_RESET_LIMIT) { + FormTimerMgr::GetInstance().HandleResetLimiter(); + } else if (type == Constants::TYPE_STATIC_UPDATE) { + long updateTime = want.GetLongParam(Constants::KEY_WAKEUP_TIME, -1); + if (updateTime < 0) { + APP_LOGE("%{public}s failed, invalid updateTime:%{public}ld.", __func__, updateTime); + return; + } + FormTimerMgr::GetInstance().OnUpdateAtTrigger(updateTime); + } else if (type == Constants::TYPE_DYNAMIC_UPDATE) { + long updateTime = want.GetLongParam(Constants::KEY_WAKEUP_TIME, 0); + if (updateTime <= 0) { + APP_LOGE("%{public}s failed, invalid updateTime:%{public}ld.", __func__, updateTime); + return; + } + FormTimerMgr::GetInstance().OnDynamicTimeTrigger(updateTime); + } else { + APP_LOGE("%{public}s failed, invalid type when action is update at timer.", __func__); + } + } else { + APP_LOGE("%{public}s failed, invalid action.", __func__); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_util.cpp b/services/formmgr/src/form_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d96831b29187174e4661f9e30ff6adb6262e962 --- /dev/null +++ b/services/formmgr/src/form_util.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "form_constants.h" +#include "form_util.h" +#include "ohos_account_kits.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std; +using namespace std::chrono; + +constexpr int64_t SEC_TO_NANOSEC = 1000000000; +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +constexpr int64_t INVALID_UDID_HASH = 0; +/** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ +void FormUtil::CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, +Want &want) +{ + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, specificationId); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, isTemporaryForm); +} + +/** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param connectId connect id. + */ +void FormUtil::CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t connectId) +{ + want.SetParam(Constants::FORM_CONNECT_ID, connectId); + want.SetParam(Constants::FORM_SUPPLY_INFO, uri); +} + +/** + * @brief create udid for form. + * @return udid. + */ +std::string FormUtil::GenerateUdid() +{ + // uuid_t uuid; + char buf[256] = {0}; + // uuid_generate(uuid); + + // uuid_unparse(uuid, buf); + return buf; +} + +/** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::GenerateFormId(int64_t udidHash) +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &t); + + int64_t elapsedTime { ((t.tv_sec) * SEC_TO_NANOSEC + t.tv_nsec) }; + size_t elapsedHash = std::hash()(std::to_string(elapsedTime)); + APP_LOGI("%{public}s, GenerateFormId generate elapsed hash %{public}zu", __func__, elapsedHash); + int64_t formId = udidHash | (int32_t)(elapsedHash & 0x000000007fffffffL); + APP_LOGI("%{public}s, GenerateFormId generate formId %{public}lld", __func__, formId); + return formId; +} + +/** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::PaddingUDIDHash(int64_t formId, int64_t udidHash) +{ + // Compatible with int form id. + if ((formId & 0xffffffff00000000L) == 0) { + return udidHash | formId; + } + + return formId; +} +/** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ +bool FormUtil::GenerateUdidHash(int64_t &udidHash) +{ + APP_LOGI("%{public}s start, udidHash: %{public}lld", __func__, udidHash); + if (udidHash != INVALID_UDID_HASH) { + return true; + } + + // std::string deviceId = GenerateUdid(); + // if (deviceId.empty()) { + // APP_LOGE("%{public}s fail, get udid failed.", __func__); + // return false; + // } + + // u_int64_t hashId = std::hash()(deviceId); + u_int64_t hashId = 0L; + const int32_t thirtyTwo = 32; + udidHash = (hashId & 0x0000000000ffffffL) << thirtyTwo; + if(udidHash < 0) { + udidHash = 0L; + } + APP_LOGI("%{public}s, FormAdapter generate hash %{public}lld", __func__, udidHash); + + return true; +} +/** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ +long FormUtil::GetCurrentNanosecond() +{ + struct timespec ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_NANOSEC + ts.tv_nsec); +} +/** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ +long FormUtil::GetCurrentMillisecond() +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC); +} +/** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ +long FormUtil::GetMillisecondFromTm(struct tm &tmAtTime) +{ + time_t inputTime = mktime(&tmAtTime); + if (inputTime == -1) { + APP_LOGE("%{public}s fail, mktime failed.", __func__); + return -1; + } + system_clock::time_point pointTime = system_clock::from_time_t(inputTime); + auto timeMilliseconds = chrono::duration_cast(pointTime.time_since_epoch()); + return timeMilliseconds.count(); +} + +/** +* @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ +std::vector FormUtil::StringSplit(const std::string &in, const std::string &delim) +{ + std::vector vEmpty; + try { + std::regex reg { delim }; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), + std::sregex_token_iterator() + }; + } catch (const std::exception& e) { + APP_LOGE("%{public}s, failed to split string.", __func__); + } + return vEmpty; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/test/BUILD.gn b/services/formmgr/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ffbcd46101e85956762e903ab73d4e2aaaa1602c --- /dev/null +++ b/services/formmgr/test/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 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("//foundation/appexecfwk/standard/appexecfwk.gni") + +config("formmgr_test_config") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "mock/include", + ] + + configs = [ + "${services_path}/formmgr:formmgr_config", + "${common_path}:appexecfwk_common_config", + ] +} + +public_configs = [ + ":formmgr_test_config", + "//utils/native/base:utils_config", +] + +public_deps = [ + "${common_path}:libappexecfwk_common", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", +] + +group("unittest") { + testonly = true + + deps = [ + "unittest/fms_form_cache_mgr_test:unittest", + "unittest/fms_form_data_mgr_test:unittest", + "unittest/fms_form_db_record_test:unittest", + "unittest/fms_form_host_record_test:unittest", + "unittest/fms_form_mgr_add_form_test:unittest", + "unittest/fms_form_mgr_cast_temp_form_test:unittest", + "unittest/fms_form_mgr_delete_form_test:unittest", + "unittest/fms_form_mgr_lifecycle_update_test:unittest", + "unittest/fms_form_mgr_message_event_test:unittest", + "unittest/fms_form_mgr_notify_invisible_forms_test:unittest", + "unittest/fms_form_mgr_notify_visible_forms_test:unittest", + "unittest/fms_form_mgr_release_form_test:unittest", + "unittest/fms_form_mgr_request_form_test:unittest", + "unittest/fms_form_mgr_update_form_test:unittest", + "unittest/fms_form_provider_data_test:unittest", + "unittest/fms_form_provider_mgr_test:unittest", + "unittest/fms_form_set_next_refresh_test:unittest", + "unittest/fms_form_sys_event_receiver_test:unittest", + "unittest/fms_form_timer_mgr_test:unittest", + ] +} diff --git a/services/formmgr/test/mock/include/mock_ability_manager.h b/services/formmgr/test/mock/include/mock_ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..a64fbb6ae1f37c5ca84f0e97fa7606cb6196a3e4 --- /dev/null +++ b/services/formmgr/test/mock/include/mock_ability_manager.h @@ -0,0 +1,552 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H +#define FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H + +#include +#include + +#include "ability_manager_interface.h" +#include "mock_form_provider_client.h" +#include "semaphore_ex.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAbilityMgrProxy : public IRemoteProxy { +public: + explicit MockAbilityMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~MockAbilityMgrProxy() = default; + virtual int UpdateConfiguration(const AAFwk::DummyConfiguration &config) override + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, int requestCode = -1) + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, const sptr &callerToken, int requestCode = -1) + { + return 0; + } + virtual int TerminateAbility( + const sptr &token, int resultCode, const AAFwk::Want *resultWant = nullptr) + { + return 0; + } + virtual int ConnectAbility( + const AAFwk::Want &want, const sptr &connect, const sptr &callerToken) + { + return 0; + } + virtual int DisconnectAbility(const sptr &connect) + { + return 0; + } + virtual sptr AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) + { + return nullptr; + } + virtual int ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) + { + return 0; + } + virtual void AddWindowInfo(const sptr &token, int32_t windowToken) + { + return; + } + virtual int AttachAbilityThread(const sptr &scheduler, const sptr &token) + { + return 0; + } + virtual int AbilityTransitionDone(const sptr &token, int state) + { + return 0; + } + virtual int GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) override + { + return 0; + } + virtual int PowerOff() override + { + return 0; + } + virtual int PowerOn() override + { + return 0; + } + virtual int lockMission(int missionId) + { + return 0; + } + virtual int UnlockMission(int missionId) override + { + return 0; + } + virtual int SetMissionDescriptionInfo( + const sptr &token, const AAFwk::MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + virtual int GetMissionLockModeState() override + { + return 0; + } + virtual sptr GetWantSender( + const AAFwk::WantSenderInfo &wantSenderInfo, const sptr &callerToken) override + { + return nullptr; + } + virtual int SendWantSender(const sptr &target, const AAFwk::SenderInfo &senderInfo) override + { + return 0; + } + virtual void CancelWantSender(const sptr &sender) override + { + return; + } + virtual int GetPendingWantUid(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantUserId(const sptr &target) override + { + return 0; + } + virtual std::string GetPendingWantBundleName(const sptr &target) override + { + return ""; + } + virtual int GetPendingWantCode(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantType(const sptr &target) override + { + return 0; + } + virtual void RegisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual void UnregisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual int GetPendingRequestWant(const sptr &target, std::shared_ptr &want) override + { + return 0; + } + virtual int ScheduleConnectAbilityDone(const sptr &token, const sptr &remoteObject) + { + return 0; + } + virtual int ScheduleDisconnectAbilityDone(const sptr &token) + { + return 0; + } + virtual int ScheduleCommandAbilityDone(const sptr &token) + { + return 0; + } + virtual void DumpState(const std::string &args, std::vector &state) + { + return; + } + virtual int TerminateAbilityResult(const sptr &token, int startId) + { + return 0; + } + virtual int StopServiceAbility(const AAFwk::Want &want) + { + return 0; + } + virtual int GetAllStackInfo(AAFwk::StackInfo &stackInfo) + { + return 0; + } + virtual int GetMissionSnapshot(const int32_t missionId, AAFwk::MissionSnapshotInfo &snapshot) + { + return 0; + } + virtual int MoveMissionToTop(int32_t missionId) + { + return 0; + } + /** + * Requires that tasks associated with a given capability token be moved to the background + * + * @param token ability token + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToEnd(const sptr &token, const bool nonFirst) + { + return 0; + } + virtual int RemoveMission(int id) + { + return 0; + } + virtual int RemoveStack(int id) + { + return 0; + } + virtual int KillProcess(const std::string &bundleName) + { + return 0; + } + virtual int UninstallApp(const std::string &bundleName) + { + return 0; + } + virtual int TerminateAbilityByRecordId(const int64_t recordId = -1) + { + return 0; + } + virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) + { + return 0; + } + /** Checks whether this ability is the first ability in a mission. + * @param lostToken, the token of ability + * @return Returns true is first in Mission. + */ + virtual bool IsFirstInMission(const sptr &token) + { + return 0; + } + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) + { + return 0; + } +}; + +class MockAbilityMgrStub : public IRemoteStub { +public: + using Uri = OHOS::Uri; + MockAbilityMgrStub() = default; + virtual ~MockAbilityMgrStub() = default; + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override + { + return 0; + } +}; +class MockAbilityMgrService : public MockAbilityMgrStub { +public: + void Wait() + { + sem_.Wait(); + } + + int Post() + { + sem_.Post(); + return 0; + } + + void PostVoid() + { + sem_.Post(); + } + + virtual int UpdateConfiguration(const AAFwk::DummyConfiguration &config) override + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, int requestCode = -1) + { + return 0; + } + virtual int StartAbility(const AAFwk::Want &want, const sptr &callerToken, int requestCode = -1) + { + return 0; + } + virtual int TerminateAbility( + const sptr &token, int resultCode, const AAFwk::Want *resultWant = nullptr) + { + return 0; + } + virtual int ConnectAbility( + const AAFwk::Want &want, const sptr &connect, const sptr &callerToken) + { + connect->OnAbilityConnectDone(want.GetElement(), new (std::nothrow) MockFormProviderClient(), 0); + return 0; + } + virtual int DisconnectAbility(const sptr &connect) + { + return 0; + } + virtual sptr AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) + { + return nullptr; + } + virtual int ReleaseDataAbility( + sptr dataAbilityScheduler, const sptr &callerToken) + { + return 0; + } + virtual void AddWindowInfo(const sptr &token, int32_t windowToken) + { + return; + } + virtual int AttachAbilityThread(const sptr &scheduler, const sptr &token) + { + return 0; + } + virtual int AbilityTransitionDone(const sptr &token, int state) + { + return 0; + } + virtual int ScheduleConnectAbilityDone(const sptr &token, const sptr &remoteObject) + { + return 0; + } + virtual int ScheduleDisconnectAbilityDone(const sptr &token) + { + return 0; + } + virtual int ScheduleCommandAbilityDone(const sptr &token) + { + return 0; + } + virtual void DumpState(const std::string &args, std::vector &state) + { + return; + } + virtual int TerminateAbilityResult(const sptr &token, int startId) + { + return 0; + } + virtual int StopServiceAbility(const AAFwk::Want &want) + { + return 0; + } + virtual int GetAllStackInfo(AAFwk::StackInfo &stackInfo) + { + return 0; + } + // virtual int GetRecentMissions( + // const int32_t numMax, const int32_t flags, std::vector &recentList) + // { + // return 0; + // } + virtual int GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) override + { + return 0; + } + virtual int PowerOff() override + { + return 0; + } + virtual int PowerOn() override + { + return 0; + } + virtual int LockMission(int missionId) override + { + return 0; + } + virtual int UnlockMission(int missionId) override + { + return 0; + } + virtual int SetMissionDescriptionInfo( + const sptr &token, const AAFwk::MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + virtual int GetMissionLockModeState() override + { + return 0; + } + virtual sptr GetWantSender( + const AAFwk::WantSenderInfo &wantSenderInfo, const sptr &callerToken) override + { + return nullptr; + } + virtual int SendWantSender(const sptr &target, const AAFwk::SenderInfo &senderInfo) override + { + return 0; + } + virtual void CancelWantSender(const sptr &sender) override + { + return; + } + virtual int GetPendingWantUid(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantUserId(const sptr &target) override + { + return 0; + } + virtual std::string GetPendingWantBundleName(const sptr &target) override + { + return ""; + } + virtual int GetPendingWantCode(const sptr &target) override + { + return 0; + } + virtual int GetPendingWantType(const sptr &target) override + { + return 0; + } + virtual void RegisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual void UnregisterCancelListener( + const sptr &sender, const sptr &receiver) override + { + return; + } + virtual int GetPendingRequestWant(const sptr &target, std::shared_ptr &want) override + { + return 0; + } + virtual int GetMissionSnapshot(const int32_t missionId, AAFwk::MissionSnapshotInfo &snapshot) + { + return 0; + } + virtual int MoveMissionToTop(int32_t missionId) + { + return 0; + } + /** + * Requires that tasks associated with a given capability token be moved to the background + * + * @param token ability token + * @param nonFirst If nonfirst is false and not the lowest ability of the mission, you cannot move mission to end + * @return Returns ERR_OK on success, others on failure. + */ + virtual int MoveMissionToEnd(const sptr &token, const bool nonFirst) + { + return 0; + } + virtual int RemoveMission(int id) + { + return 0; + } + virtual int RemoveStack(int id) + { + return 0; + } + virtual int KillProcess(const std::string &bundleName) + { + return 0; + } + virtual int UninstallApp(const std::string &bundleName) + { + return 0; + } + virtual int TerminateAbilityByRecordId(const int64_t recordId = -1) + { + return 0; + } + virtual int TerminateAbilityByCaller(const sptr &callerToken, int requestCode) + { + return 0; + } + int MoveMissionToFloatingStack(const MissionOption &missionOption) + { + return 0; + } + int MoveMissionToSplitScreenStack(const MissionOption &missionOption) + { + return 0; + } + int MinimizeMultiWindow(int missionId) + { + return 0; + } + int MaximizeMultiWindow(int missionId) + { + return 0; + } + int GetFloatingMissions(std::vector &list) + { + return 0; + } + int CloseMultiWindow(int missionId) + { + return 0; + } + int SetMissionStackSetting(const StackSetting &stackSetting) + { + return 0; + } + int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode = 0) + { + return 0; + } + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) + { + return 0; + } + + /** Checks whether this ability is the first ability in a mission. + * @param lostToken, the token of ability + * @return Returns true is first in Mission. + */ + virtual bool IsFirstInMission(const sptr &token) + { + return 0; + } + /** + * Checks whether a specified permission has been granted to the process identified by pid and uid + * + * @param permission Indicates the permission to check. + * @param pid Indicates the ID of the process to check. + * @param uid Indicates the UID of the process to check. + * @param message Describe success or failure + * + * @return Returns ERR_OK on success, others on failure. + */ + virtual int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) + { + return 0; + } + +private: + Semaphore sem_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_MOCK_APP_MGR_HOST_H \ No newline at end of file diff --git a/services/formmgr/test/mock/include/mock_bundle_manager.h b/services/formmgr/test/mock/include/mock_bundle_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..5a3ec17f10924d8bff5648c05244d6d8e29e46c3 --- /dev/null +++ b/services/formmgr/test/mock/include/mock_bundle_manager.h @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2021 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_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H +#define OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H + +#include + +#include "ability_info.h" +#include "application_info.h" +#include "bundle_mgr_interface.h" +#include "gmock/gmock.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "ohos/aafwk/content/want.h" + +namespace OHOS { +namespace AppExecFwk { +class BundleMgrProxy : public IRemoteProxy { +public: + explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + virtual ~BundleMgrProxy() + {} + MOCK_METHOD3( + CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + bool(const std::string &bundleName, const std::string &permission, const int userId)); + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); + MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override + { + return true; + } + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override + { + return true; + } + + std::string GetAppType(const std::string &bundleName) override + { + return "system"; + } + + virtual bool GetApplicationInfo(const std::string &appName, const ApplicationFlag flag, const int userId, + ApplicationInfo &appInfo) override + { + return true; + } + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + } + + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override + { + return true; + } + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override + { + if (bundleName.compare("com.form.host.app600") == 0) { + return 600; + } + return 0; + } + virtual std::string GetAppIdByBundleName(const std::string &bundleName, const int userId) override + { + return ""; + } + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "com.form.provider.service"; + return true; + } + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override + { + return true; + } + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + } + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + } + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + } + + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + } + + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + } + + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + } + + virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override + { + return 0; + } + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + } + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + } + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + } + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + } + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + } + virtual bool IsSafeMode() override + { + return true; + } + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + } + virtual bool CleanBundleDataFiles(const std::string &bundleName) override + { + return true; + } + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + } + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + } + virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override + { + return true; + } + virtual sptr GetBundleInstaller() override + { + return nullptr; + } + + /** + * @brief Obtains information about the shortcuts of the application. + * @param bundleName Indicates the name of the bundle to shortcut. + * @param form Indicates the callback a list to shortcutinfo. + * @return Returns true if shortcutinfo get success + */ + virtual bool GetShortcutInfos(const std::string &bundleName,std::vector &shortcut) override{ + return true; + } + // /** + // * @brief Starts a shortcut based on the given shortcut ID and bundle name. + // * @param bundleName BundleName Indicates the bundle name of the application to which the shortcut belongs. + // * @param shortcutId Starts a shortcut based on the given shortcut ID and bundle name. + // * @return Returns true if StartShortcut get success + // */ + // virtual bool StartShortcut(const std::string &shortcutId, const std::string &bundleName) override{ + // return true; + // } + /** + * @brief Disables specified home-screen shortcuts that are no longer used. + * @param shortcutIds Indicates the list of shortcut IDs to be disabled. + * @return Returns true if disableHomeShortcuts get success + */ + // virtual bool DisableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + // /** + // * @brief Enables specified home-screen shortcuts. + // * @param shortcutIds Indicates the list of shortcut IDs to be enabled. + // * @return Returns true if enableHomeShortcuts? get success + // */ + // virtual bool EnableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + // /** + // * @brief Checks whether a shortcut can be added to the home screen where the application is located. + // * @return Returns true if a shortcut can be added to the home screen; returns false otherwise. + // */ + // virtual bool IsHomeShortcutSupportes() override{ + // return true; + // } + // /** + // * @brief Adds a home-screen shortcut that will be fixed on the home screen. + // * @param shortcutInfo Indicates the ShortcutInfo object containing information about the home-screen + // * shortcut to add. The id, label, and intent attributes of this parameter must be specified. + // * @return Returns true if the shortcut is successfully added; returns false otherwise. + // */ + // virtual bool AddHomeShortcut(ShortcutInfo &shortcutInfo) override{ + // return true; + // } + // /** + // * @brief Updates information about specified home-screen shortcuts that have been added. + // * @param shortcutInfos Updates information about specified home-screen shortcuts that have been added. + // * @return Returns true if the operation is successful; returns false otherwise. + // */ + // virtual bool UpdateShortcuts(std::vector &shortcutInfos) override{ + // return true; + // } + // /** + // * @brief Checks whether a specified shortcut is available. + // * @param shortcutId Indicates the ID of the shortcut to check. + // * @param flag Indicates the type of the shortcut to check. Currently, only the home-screen shortcut + // * IBundleManager#QUERY_SHORTCUT_HOME is available. + // * @return Returns IBundleManager#SHORTCUT_EXISTENCE_EXISTS if the specified shortcut is available; returns + // * IBundleManager#SHORTCUT_EXISTENCE_NOT_EXISTS if it is not available; + // * returns IBundleManager.SHORTCUT_EXISTENCE_UNKNOW if an error occurs. + // */ + // virtual int IsShortcutExist(const std::string &shortcutId, const int &flag) override{ + // return 0; + // } + /** + * @brief Obtain the HAP module info of a specific ability. + * @param abilityInfo Indicates the ability. + * @param hapModuleInfo Indicates the obtained HapModuleInfo object. + * @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise. + */ + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + + virtual bool CheckIsSystemAppByUid(const int uid) override + { + if (uid == 600) { + return false; + } + return true; + } + virtual bool IsApplicationEnabled(const std::string &bundleName)override + { + return true; + } + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + } + + virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; + virtual bool GetAllFormsInfo(std::vector &formInfo) override; + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) override; + virtual bool GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfo) override; +}; + +class BundleMgrStub : public IRemoteStub { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"IBundleMgr"); + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +}; + +class BundleMgrService : public BundleMgrStub { +public: + MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); + MOCK_METHOD2(CheckPermission, int(const std::string &bundleName, const std::string &permission)); + MOCK_METHOD1(CleanBundleDataFiles, bool(const std::string &bundleName)); + MOCK_METHOD3( + CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); + MOCK_METHOD3(RequestPermissionFromUser, + bool(const std::string &bundleName, const std::string &permission, const int userId)); + MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); + MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); + MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); + MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); + MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); + MOCK_METHOD2(RegisterPermissionsChanged, + bool(const std::vector &uids, const sptr &callback)); + MOCK_METHOD1(UnregisterPermissionsChanged, bool(const sptr &callback)); + bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override; + bool QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) override; + + std::string GetAppType(const std::string &bundleName) override; + virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override; + + virtual bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; + virtual bool GetApplicationInfos( + const ApplicationFlag flag, const int userId, std::vector &appInfos) override + { + return true; + }; + virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override; + virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override + { + return true; + }; + virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override + { + bundleName = "com.form.provider.service"; + return true; + }; + virtual bool GetBundleGids(const std::string &bundleName, std::vector &gids) override; + virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector &bundleInfos) override + { + return true; + }; + virtual bool QueryKeepAliveBundleInfos(std::vector &bundleInfos) override + { + return true; + }; + virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override + { + return ""; + }; + // obtains information about an application bundle contained in a ohos Ability Package (HAP). + virtual bool GetBundleArchiveInfo( + const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override + { + return true; + }; + virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override + { + return true; + } + // obtains the Want for starting the main ability of an application based on the given bundle name. + virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override + { + return true; + }; + // checks whether the publickeys of two bundles are the same. + virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override + { + return 0; + }; + // checks whether a specified bundle has been granted a specific permission. + virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override + { + return true; + }; + virtual bool GetAllPermissionGroupDefs(std::vector &permissionDefs) override + { + return true; + }; + virtual bool GetAppsGrantedPermissions( + const std::vector &permissions, std::vector &appNames) override + { + return true; + }; + virtual bool HasSystemCapability(const std::string &capName) override + { + return true; + }; + virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override + { + return true; + }; + virtual bool IsSafeMode() override + { + return true; + }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; + + virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override + { + return true; + }; + // unregister callback of all application + virtual bool UnregisterBundleStatusCallback() override + { + return true; + }; + virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override + { + return true; + }; + virtual sptr GetBundleInstaller() override + { + return nullptr; + }; + virtual bool IsApplicationEnabled(const std::string &bundleName) override + { + return true; + }; + virtual bool CheckIsSystemAppByUid(const int uid) override + { + if (uid == 600) { + return false; + } + + return true; + }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + }; + + /** + * @brief Obtains information about the shortcuts of the application. + * @param bundleName Indicates the name of the bundle to shortcut. + * @param form Indicates the callback a list to shortcutinfo. + * @return Returns true if shortcutinfo get success + */ + virtual bool GetShortcutInfos(const std::string &bundleName,std::vector &shortcut) override{ + return true; + } + // /** + // * @brief Starts a shortcut based on the given shortcut ID and bundle name. + // * @param bundleName BundleName Indicates the bundle name of the application to which the shortcut belongs. + // * @param shortcutId Starts a shortcut based on the given shortcut ID and bundle name. + // * @return Returns true if StartShortcut get success + // */ + // virtual bool StartShortcut(const std::string &shortcutId, const std::string &bundleName) override{ + // return true; + // } + // /** + // * @brief Disables specified home-screen shortcuts that are no longer used. + // * @param shortcutIds Indicates the list of shortcut IDs to be disabled. + // * @return Returns true if disableHomeShortcuts get success + // */ + // virtual bool DisableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + // /** + // * @brief Enables specified home-screen shortcuts. + // * @param shortcutIds Indicates the list of shortcut IDs to be enabled. + // * @return Returns true if enableHomeShortcuts? get success + // */ + // virtual bool EnableHomeShortcuts(std::vector &shortcutIds) override{ + // return true; + // } + /** + * @brief Checks whether a shortcut can be added to the home screen where the application is located. + * @return Returns true if a shortcut can be added to the home screen; returns false otherwise. + */ + // virtual bool IsHomeShortcutSupportes() override{ + // return true; + // } + // /** + // * @brief Adds a home-screen shortcut that will be fixed on the home screen. + // * @param shortcutInfo Indicates the ShortcutInfo object containing information about the home-screen shortcut + // * to add. The id, label, and intent attributes of this parameter must be specified. + // * @return Returns true if the shortcut is successfully added; returns false otherwise. + // */ + // virtual bool AddHomeShortcut(ShortcutInfo &shortcutInfo) override{ + // return true; + // } + // /** + // * @brief Updates information about specified home-screen shortcuts that have been added. + // * @param shortcutInfos Updates information about specified home-screen shortcuts that have been added. + // * @return Returns true if the operation is successful; returns false otherwise. + // */ + // virtual bool UpdateShortcuts(std::vector &shortcutInfos) override{ + // return true; + // } + // /** + // * @brief Checks whether a specified shortcut is available. + // * @param shortcutId Indicates the ID of the shortcut to check. + // * @param flag Indicates the type of the shortcut to check. Currently, only the home-screen shortcut + // * IBundleManager#QUERY_SHORTCUT_HOME is available. + // * @return Returns IBundleManager#SHORTCUT_EXISTENCE_EXISTS if the specified shortcut is available; returns + // * IBundleManager#SHORTCUT_EXISTENCE_NOT_EXISTS if it is not available; returns + // * IBundleManager.SHORTCUT_EXISTENCE_UNKNOW if an error occurs. + // */ + // virtual int IsShortcutExist(const std::string &shortcutId, const int &flag) override{ + // return 0; + // } + + virtual bool GetAllFormsInfo(std::vector &formInfo) override; + virtual bool GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) override; + virtual bool GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, + std::vector &formInfo) override; + virtual bool QueryAbilityInfos(const Want &want, std::vector &abilityInfos) override + { + return true; + }; + virtual bool GetModuleUsageRecords( + const int32_t number, std::vector &moduleUsageRecords) override + { + return true; + } + virtual bool NotifyActivityLifeStatus( + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime) override + { + return true; + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H diff --git a/services/formmgr/test/mock/include/mock_form_death_callback.h b/services/formmgr/test/mock/include/mock_form_death_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..2563698580783f0e12d037f88958f0e071577f2e --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_death_callback.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_DEATH_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_DEATH_CALLBACK_H + +#include +#include +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "event_handler.h" +#include "form_constants.h" +#include "form_death_callback.h" +#include "form_mgr_stub.h" +#include "form_js_info.h" +#include "form_provider_data.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class MockFormDeathCallback. + * The MockFormDeathCallback for form mgr test. + */ +class MockFormDeathCallback : public FormDeathCallback { +public: + MockFormDeathCallback() = default; + virtual ~MockFormDeathCallback() = default; + + void OnDeathReceived() + { + APP_LOGI("%{public}s called.", __func__); + } + + void OnReconnectFailed() + { + APP_LOGI("%{public}s called.", __func__); + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_MOCK_FORM_DEATH_CALLBACK_H diff --git a/services/formmgr/test/mock/include/mock_form_host_client.h b/services/formmgr/test/mock/include/mock_form_host_client.h new file mode 100644 index 0000000000000000000000000000000000000000..7d7f08d5df2a146bfa55fb2cd719f895ecb1a286 --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_host_client.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H + +#include +// #include "ability.h" +#include "form_host_stub.h" +#include "iremote_object.h" +#include "iremote_stub.h" +#include "semaphore_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class MockFormHostClient + * MockFormHostClient. + */ +class MockFormHostClient : public FormHostStub { +public: + MockFormHostClient() = default; + virtual ~MockFormHostClient() = default; + + void Wait() + { + sem_.Wait(); + } + + int Post() + { + sem_.Post(); + return 0; + } + + void PostVoid() + { + sem_.Post(); + } + + // void AddForm(const Ability& slice, int64_t formId); + + // void RemoveForm(const Ability& slice, int64_t formId); + + // bool ContainsForm(int64_t formId); + /** + * Request to give back a Form. + * + * @param formId, The Id of the forms to create. + * @param formInfo, Form info. + * @return none. + */ + virtual void OnAcquired(const FormJsInfo &formInfo) override; + + /** + * Form is updated. + * + * @param formId, The Id of the form to update. + * @param formInfo, Form info. + * @return none. + */ + virtual void OnUpdate(const FormJsInfo &formInfo) override; + + /** + * Form provider is uninstalled. + * + * @param formIds, The Id list of the forms. + * @return none. + */ + virtual void OnUninstall(const std::vector &formIds) override; + +private: + +private: + Semaphore sem_; + DISALLOW_COPY_AND_MOVE(MockFormHostClient); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_HOST_CLIENT_H diff --git a/services/formmgr/test/mock/include/mock_form_provider_client.h b/services/formmgr/test/mock/include/mock_form_provider_client.h new file mode 100644 index 0000000000000000000000000000000000000000..8f8a6857d373b5b5d07ead573ec3f8c5126b905f --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_provider_client.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H + +#include +#include +#include +#include "form_provider_stub.h" + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderStub + * FormProviderStub. + */ +class MockFormProviderClient : public FormProviderStub { +public: + MockFormProviderClient() = default; + virtual ~MockFormProviderClient() = default; + +private: + /** + * Acquire to give back an ProviderFormInfo. This is sync API. + * + * @param want, Indicates the {@link Want} structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int AcquireProviderFormInfo(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * Notify provider when the form was deleted. + * + * @param formId, The Id of the form. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int NotifyFormDelete(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * Notify provider when the form was deleted. + * + * @param formIds, The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int NotifyFormsDelete(const std::vector &formIds, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + */ + virtual int NotifyFormUpdate(const int64_t formId, const Want &want, + const sptr &callerToken) override; + + /** + * @brief Event notify when change the form visible. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) override; + + /** + * Notify provider when the temp form was cast to normal form. + * + * @param formId, The Id of the form to update. + * @param callerToken, Caller ability token. + * @return none. + */ + virtual int NotifyFormCastTempForm(const int64_t formId, const Want &want, + const sptr &callerToken) override; + /** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int FireFormEvent(const int64_t formId, const std::string &message, const Want &want, + const sptr &callerToken) override; +private: + DISALLOW_COPY_AND_MOVE(MockFormProviderClient); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_CLIENT_H diff --git a/services/formmgr/test/mock/include/mock_form_token.h b/services/formmgr/test/mock/include/mock_form_token.h new file mode 100644 index 0000000000000000000000000000000000000000..ca655e5f44f2ac7e460c7b3cb87af05515551e3b --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_token.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_TOKEN_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_TOKEN_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +class IFormToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormToken"); +}; + +class MockFormToken : public IRemoteStub { +public: + MockFormToken() = default; + virtual ~MockFormToken() = default; + + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + return 0; + } + +private: + DISALLOW_COPY_AND_MOVE(MockFormToken); +}; + +class FormTokenProxy : public IRemoteProxy { +public: + explicit FormTokenProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~FormTokenProxy() = default; + +private: + DISALLOW_COPY_AND_MOVE(FormTokenProxy); +}; + +DECLARE_INTERFACE_DESCRIPTOR(u"IFormToken"); +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_TOKEN_H diff --git a/services/formmgr/test/mock/include/mock_form_user_manager.h b/services/formmgr/test/mock/include/mock_form_user_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f60c1ad8659f889d26aaf471eab897529c596bc1 --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_user_manager.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_USER_MANAGER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_USER_MANAGER_H + + +#include + +#include "form_info.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "form_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class IFormUserMgr : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.FormUserMgr"); + /** + * Update form with formId, send formId to form manager service. + * + * @param formId, The Id of the form to update. + * @param bundleName, Provider ability bundleName. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const FmsFormInfo &formInfo) = 0; +}; + +class FormUserMgrProxy : public IRemoteProxy { +public: + explicit FormUserMgrProxy(const sptr &impl) : IRemoteProxy(impl) + {} + virtual ~FormUserMgrProxy() + {} + /** + * Update form with formId, send formId to form manager service. + * + * @param formId, The Id of the form to update. + * @param bundleName, Provider ability bundleName. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const FmsFormInfo &formInfo) override + { + return ERR_OK; + } +}; + +class FormUserMgrStub : public IRemoteStub { +public: + FormUserMgrStub(); + virtual ~FormUserMgrStub(); + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +private: + int32_t HandleUpdateForm(MessageParcel &data, MessageParcel &reply); +}; + +class FormUserMgrService : public FormUserMgrStub { +public: + void OnStart() override; + void OnStop() override; + + /** + * Update form with formId, send formId to form manager service. + * + * @param formId, The Id of the form to update. + * @param bundleName, Provider ability bundleName. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int UpdateForm(const int64_t formId, const FmsFormInfo &formInfo) override + { + return ERR_OK; + } +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_TEST_MOCK_INCLUDE_MOCK_FORM_USER_MANAGER_H diff --git a/services/formmgr/test/mock/src/mock_bundle_manager.cpp b/services/formmgr/test/mock/src/mock_bundle_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4905e226128237654beeb5e4eac41b12840d4420 --- /dev/null +++ b/services/formmgr/test/mock/src/mock_bundle_manager.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2021 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 "mock_bundle_manager.h" + +#include "ability_info.h" +#include "application_info.h" +#include "form_info.h" + +namespace OHOS { +namespace AppExecFwk { +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; +const std::string DEVICE_ID = "ohos-phone1"; + +bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) +{ + return true; +} + +int BundleMgrService::GetUidByBundleName(const std::string &bundleName, const int userId) +{ + if (bundleName.compare("com.form.host.app600") == 0) { + return 600; + } + return 0; +} + +bool BundleMgrProxy::GetAllFormsInfo(std::vector &formInfo) +{ + return true; +} +bool BundleMgrProxy::GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) +{ + return true; +} +bool BundleMgrProxy::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, +std::vector &formInfo) +{ + return true; +} + +int BundleMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + return 0; +} + +bool BundleMgrService::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) +{ + return true; +} + +bool BundleMgrService::QueryAbilityInfoByUri(const std::string &uri, AbilityInfo &abilityInfo) +{ + return false; +} + +bool BundleMgrService::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + return true; +} + +std::string BundleMgrService::GetAppType(const std::string &bundleName) +{ + return "system"; +} + +bool BundleMgrService::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) +{ + std::vector abilityInfos; + ApplicationInfo applicationInfo; + ModuleInfo moduleInfo; + + moduleInfo.moduleSourceDir = FORM_PROVIDER_MODULE_SOURCE_DIR; + moduleInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + bundleInfo.name = bundleName; + applicationInfo.bundleName = bundleName; + applicationInfo.moduleInfos.emplace_back(moduleInfo); + bundleInfo.applicationInfo = applicationInfo; + + bundleInfo.moduleNames.emplace_back(PARAM_PROVIDER_MODULE_NAME); + + AbilityInfo abilityInfo; + abilityInfo.name = FORM_PROVIDER_ABILITY_NAME; + abilityInfo.package = PARAM_PROVIDER_PACKAGE_NAME; + abilityInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + abilityInfo.deviceId = DEVICE_ID; + bundleInfo.abilityInfos.emplace_back(abilityInfo); + + return true; +} +bool BundleMgrService::GetBundleGids(const std::string &bundleName, std::vector &gids) +{ + return true; +} + +bool BundleMgrService::GetAllFormsInfo(std::vector &formInfo) +{ + return true; +} +bool BundleMgrService::GetFormsInfoByApp(const std::string &bundleName, std::vector &formInfo) +{ + FormInfo form; + form.bundleName = bundleName; + form.abilityName = FORM_PROVIDER_ABILITY_NAME; + form.moduleName = PARAM_PROVIDER_MODULE_NAME; + form.name = PARAM_FORM_NAME; + form.updateEnabled = true; + form.updateDuration = 1; + form.scheduledUpateTime = "06:06"; + form.jsComponentName = FORM_JS_COMPOMENT_NAME; + form.formVisibleNotify = true; + form.supportDimensions = {1, 2}; + form.defaultDimension = 1; + formInfo.emplace_back(form); + return true; +} +bool BundleMgrService::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, +std::vector &formInfo) +{ + FormInfo form; + form.bundleName = bundleName; + form.abilityName = FORM_PROVIDER_ABILITY_NAME; + form.moduleName = PARAM_PROVIDER_MODULE_NAME; + form.name = PARAM_FORM_NAME; + form.updateEnabled = true; + form.updateDuration = 1; + form.scheduledUpateTime = "06:06"; + form.jsComponentName = FORM_JS_COMPOMENT_NAME; + form.formVisibleNotify = true; + form.supportDimensions = {1, 2}; + form.defaultDimension = 1; + formInfo.emplace_back(form); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/mock/src/mock_form_host_client.cpp b/services/formmgr/test/mock/src/mock_form_host_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ad90b9ad4c6e7a0874c391b33f68012696ce8153 --- /dev/null +++ b/services/formmgr/test/mock/src/mock_form_host_client.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "errors.h" +#include "mock_form_host_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +// void MockFormHostClient::AddForm(const Ability& slice, int64_t formId){ + +// } + +// void MockFormHostClient::RemoveForm(const Ability& slice, int64_t formId{ + +// } + +// bool MockFormHostClient::ContainsForm(int64_t formId){ +// return false; +// } + +/** + * Request to give back a Form. + * + * @param formInfo, Form info. + * @return none. + */ +void MockFormHostClient::OnAcquired(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnAcquired"); + + int64_t formId = formInfo.formId; + ASSERT_FALSE(formId == 0); + PostVoid(); +} + +/** +* Form is updated. +* +* @param bundleName, Provider ability bundleName. +* @return none. +*/ +void MockFormHostClient::OnUpdate(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnUpdate"); + PostVoid(); +} + + +/** + * Form provider is uninstalled + * + * @param formIds, The Id list of the forms. + * @return none. + */ +void MockFormHostClient::OnUninstall(const std::vector &formIds) +{ + APP_LOGD("MockFormHostClient OnUnInstall"); + PostVoid(); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/mock/src/mock_form_provider_client.cpp b/services/formmgr/test/mock/src/mock_form_provider_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b94d46ec1df787e6f0f045ac58248443d70c401 --- /dev/null +++ b/services/formmgr/test/mock/src/mock_form_provider_client.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "errors.h" +#include "form_constants.h" +#include "form_supply_interface.h" +#include "mock_form_provider_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Acquire to give back an ProviderFormInfo. This is sync API. + * + * @param want, The want of the form to create. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::AcquireProviderFormInfo(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + // avoid the user modify the number in onCreate + + APP_LOGD("Acquire provider form info"); + + sptr formSupply = iface_cast(callerToken); + if (formSupply == nullptr) { + APP_LOGE("failed to get formSupplyProxy"); + } + // Want newWant; + // newWant.SetElement(want.GetElement()); + // long formId = want.GetLongParam(Constants::PARAM_FORM_IDENTITY_KEY, 0); + // APP_LOGD("AcquireProviderFormInfo, formId:%{public}ld", formId); + + // newWant.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, formId); + + // int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); + // newWant.SetParam(Constants::ACQUIRE_TYPE, type); + FormProviderInfo formProviderInfo; + formSupply->OnAcquire(formProviderInfo, want); + return ERR_OK; +} + +/** + * Notify provider when the form was deleted. + * + * @param formId, The Id of the form. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormDelete(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify form delete"); + return ERR_OK; +} +/** + * Notify provider when the forms was deleted. + * + * @param formIds, The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormsDelete(const std::vector &formIds, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify forms delete"); + return ERR_OK; +} + +/** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + */ +int MockFormProviderClient::NotifyFormUpdate(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify form update"); + return ERR_OK; +} + +/** + * @brief Event notify when change the form visible. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) +{ + APP_LOGD("Event notify"); + return ERR_OK; +} + +/** + * Notify provider when the temp form was cast to normal form. + * + * @param formId, The Id of the form to update. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormCastTempForm(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify cast temp form"); + return ERR_OK; +} +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Fire form event"); + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/unittest/fms_form_cache_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_cache_mgr_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b3153757f91b1cb6b15f7cf2ae6a1921171dab1c --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_cache_mgr_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormCacheMgrTest") { + module_out_path = module_output_path + + sources = [ "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormCacheMgrTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5942712a56984e81f3c5b0475871d376fc20dd26 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#define private public +#include "form_cache_mgr.h" +#undef private + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +const int64_t PARAM_FORM_ID_FIRST = 1001; +const int64_t PARAM_FORM_ID_SECOND = 1002; + +namespace { +class FmsFormCacheMgrTest : public testing::Test { +public: + + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + FormCacheMgr formCacheMgr_; +}; + + +void FmsFormCacheMgrTest::SetUpTestCase() +{} + +void FmsFormCacheMgrTest::TearDownTestCase() +{} + +void FmsFormCacheMgrTest::SetUp() +{} + +void FmsFormCacheMgrTest::TearDown() +{} + +/* + * Feature: FormCacheMgr + * Function: GetData + * FunctionPoints: FormCacheMgr GetData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: invoke GetData works by input key. + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_001, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_001 start"); + + std::string dataResult = ""; + formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST]= "{'a':'1','b':'2'}"; + EXPECT_TRUE(formCacheMgr_.GetData(PARAM_FORM_ID_FIRST, dataResult)); + EXPECT_EQ("{'a':'1','b':'2'}", dataResult); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_001 end"; +} + +/* + * Feature: FormCacheMgr + * Function: GetData + * FunctionPoints: FormCacheMgr GetData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: can not get data by input key. + */ + +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_002, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_002 start"); + + std::string dataResult = ""; + formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST]= "{'a':'1','b':'2'}"; + EXPECT_FALSE(formCacheMgr_.GetData(PARAM_FORM_ID_SECOND, dataResult)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_002 end"; +} + +/* + * Feature: FormCacheMgr + * Function: AddData + * FunctionPoints: FormCacheMgr AddData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: add data by input param. + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_003, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_003 start"); + + std::string dataResult = "{'a':'1','b':'2'}"; + EXPECT_TRUE(formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST], dataResult); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_003 end"; +} + +/* + * Feature: FormCacheMgr + * Function: AddData + * FunctionPoints: FormCacheMgr AddData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: cache contains data and add the new data by input param. + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_004, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_004 start"); + + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + EXPECT_TRUE(formCacheMgr_.AddData(PARAM_FORM_ID_SECOND, dataResult2)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_SECOND],dataResult2); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_004 end"; +} + +/* + * Feature: FormCacheMgr + * Function: AddData + * FunctionPoints: FormCacheMgr AddData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: add data but key conflict + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_010, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_010 start"); + + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + EXPECT_FALSE(formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult2)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_010 end"; +} + +/* + * Feature: FormCacheMgr + * Function: DeleteData + * FunctionPoints: FormCacheMgr DeleteData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: delete data by input key + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_005, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_005 start"); + + std::string dataResult = ""; + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + formCacheMgr_.AddData(PARAM_FORM_ID_SECOND, dataResult2); + EXPECT_TRUE(formCacheMgr_.DeleteData(PARAM_FORM_ID_SECOND)); + EXPECT_FALSE(formCacheMgr_.GetData(PARAM_FORM_ID_SECOND, dataResult)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST], dataResult1); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_005 end"; +} + +/* + * Feature: FormCacheMgr + * Function: DeleteData + * FunctionPoints: FormCacheMgr DeleteData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: delete data but not exsit + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_006, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_006 start"); + + EXPECT_TRUE(formCacheMgr_.DeleteData(PARAM_FORM_ID_SECOND)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_006 end"; +} + +/* + * Feature: FormCacheMgr + * Function: UpdateData + * FunctionPoints: FormCacheMgr UpdateData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: update cache's data by input param + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_007, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_007 start"); + + std::string dataResult = ""; + std::string dataResult1 = "{'a':'1','b':'2'}"; + std::string dataResult2 = "{'a':'2','b':'2'}"; + formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); + EXPECT_TRUE(formCacheMgr_.UpdateData(PARAM_FORM_ID_FIRST, dataResult2)); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_FIRST], dataResult2); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_007 end"; +} + +/* + * Feature: FormCacheMgr + * Function: UpdateData + * FunctionPoints: FormCacheMgr UpdateData interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: update cache's data but not exsit key + */ +HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_008, TestSize.Level0) +{ + APP_LOGI("fms_form_cache_mgr_test_008 start"); + + std::string dataResult1 = "{'a':'1','b':'2'}"; + EXPECT_FALSE(formCacheMgr_.UpdateData(PARAM_FORM_ID_FIRST, dataResult1)); + + GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_008 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_data_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_data_mgr_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5b71a556cef3efbc654a5fdb0490f966c764571e --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/BUILD.gn @@ -0,0 +1,81 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormDataMgrTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + + #"//foundation/appexecfwk/standard/services/bundlemgr/include", + #"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + + #"//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/include", + "//foundation/appexecfwk/appexecfwk_lite/interfaces/kits/bundle_lite", + ] + + configs = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + + #"${libs_path}/libeventhandler:libeventhandler_target", + #"//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormDataMgrTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9864114ed6bcc22e2b3b9fa7995c60b52d61ff4f --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp @@ -0,0 +1,2136 @@ +/* + * Copyright (c) 2021 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#define private public +#include "form_data_mgr.h" +#undef private +#include "form_constants.h" +#include "form_record.h" +#include "mock_form_host_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_NAME = "formName"; + +namespace { +class FmsFormDataMgrTest : public testing::Test { +public: + FmsFormDataMgrTest() + {} + ~FmsFormDataMgrTest() + {} + + void SetUp(); + void TearDown(); + void InitFormItemInfo(int64_t formId, FormItemInfo &form_item_info); + +protected: + FormDataMgr formDataMgr_; + sptr token_; +}; + +void FmsFormDataMgrTest::SetUp(void) +{ + // token + token_ = new (std::nothrow) OHOS::AppExecFwk::MockFormHostClient(); +} + +void FmsFormDataMgrTest::TearDown(void) +{} + +void FmsFormDataMgrTest::InitFormItemInfo(int64_t formId, FormItemInfo &form_item_info) +{ + // create hapSourceDirs + std::vector hapSourceDirs; + std::string hapSourceDir = "1/2/3"; + hapSourceDirs.emplace_back(hapSourceDir); + + // create form_item_info + form_item_info.SetFormId(formId); + form_item_info.SetTemporaryFlag(true); + form_item_info.SetEnableUpdateFlag(true); + form_item_info.SetUpdateDuration(Constants::MIN_CONFIG_DURATION); + form_item_info.SetScheduledUpdateTime("10:30"); + form_item_info.SetHapSourceDirs(hapSourceDirs); +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_001 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * temporaryFlag is true, and tempForms is empty, then create a tempForm. + * formRecords_ is empty, then create formRecords. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_001 start"; + + int64_t formId = 1; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_002 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is include this formId. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_002 start"; + + int64_t formId = 2; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + + // create formRecords + FormRecord record = formDataMgr_.CreateFormRecord(form_item_info, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_003 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not include this formId, then create formRecords. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_003 start"; + + int64_t formId = 3; + int64_t otherformId = 100; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + + // create other FormItemInfo + FormItemInfo otherFormItemInfo; + InitFormItemInfo(otherformId, otherFormItemInfo); + + // create formRecords + FormRecord record = formDataMgr_.CreateFormRecord(otherFormItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(otherformId, record); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_004 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * EnableUpdateFlag is true, + * SetUpdateDuration is not MAX_CONFIG_DURATION.(call ParseIntervalConfig) + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_004 start"; + + int64_t formId = 4; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_004 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_005 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * EnableUpdateFlag is true, + * SetUpdateDuration is between MIN_CONFIG_DURATION and MAX_CONFIG_DURATION.(call ParseIntervalConfig) + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_005 start"; + + int64_t formId = 5; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION-2); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_005 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_006 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为empty + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_006 start"; + + int64_t formId = 6; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + form_item_info.scheduledUpdateTime_.clear(); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_006 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_007 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为无效值 + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_007 start"; + + int64_t formId = 7; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + form_item_info.SetScheduledUpdateTime("10:30:10"); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_007 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_008 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为无效值 + * 不存在hapSourceDirs_ + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_008 start"; + + int64_t formId = 8; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + form_item_info.SetScheduledUpdateTime("10:70"); + form_item_info.hapSourceDirs_.clear(); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_008 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormRecord_009 + * @tc.name: AllotFormRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * SetUpdateDuration is 0.(call ParseAtTimerConfig) + * 获取配置项scheduledUpdateTime_为有效值 + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_009, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_009 start"; + + int64_t formId = 9; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo form_item_info; + InitFormItemInfo(formId, form_item_info); + form_item_info.SetUpdateDuration(0); + + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); + EXPECT_EQ(formId, recordResult.formId); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_009 end"; +} + + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormHostRecord_001 + * @tc.name: AllotFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is include token_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_001 start"; + + int64_t formId = 1; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.AllotFormHostRecord(formItemInfo, token_, formId, callingUid)); + EXPECT_EQ(true, formDataMgr_.clientRecords_.begin()->forms_[formId]); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormHostRecord_002 + * @tc.name: AllotFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not include token_. + * CreateHostRecord is OK. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_002 start"; + + int64_t formId = 2; + int callingUid = 0; + + //create FormItemInfo + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + + EXPECT_EQ(true, formDataMgr_.AllotFormHostRecord(formItemInfo, token_, formId, callingUid)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_AllotFormHostRecord_003 + * @tc.name: AllotFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not include token_. + * CreateHostRecord is NG. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_003 start"; + + int64_t formId = 3; + int callingUid = 0; + + // create FormItemInfo + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + + // set callerToken nullptr + token_ = nullptr; + + EXPECT_EQ(false, formDataMgr_.AllotFormHostRecord(formItemInfo, token_, formId, callingUid)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormHostRecord_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CreateFormInfo_001 + * @tc.name: CreateFormInfo + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CreateFormInfo_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CreateFormInfo_001 start"; + + int64_t formId = 1; + + // create record + FormRecord record; + record.bundleName = FORM_HOST_BUNDLE_NAME; + record.abilityName = FORM_PROVIDER_ABILITY_NAME; + record.formName = FORM_NAME; + record.formTempFlg = true; + + FormJsInfo formInfo; + + formDataMgr_.CreateFormInfo(formId, record, formInfo); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CreateFormInfo_001 output=>bundleName:"< formInfos; + + EXPECT_EQ(false, formDataMgr_.GetFormRecord(bundleName, formInfos)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormRecord_2_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetFormRecord_2_002 + * @tc.name: GetFormRecord_2 + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetFormRecord_2_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormRecord_2_002 start"; + + std::string bundleName = "bundleName"; + std::vector formInfos; + + // create formRecords_ + int64_t formId = 2; + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(bundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(true, formDataMgr_.GetFormRecord(bundleName, formInfos)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormRecord_2_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HasFormUserUids_001 + * @tc.name: HasFormUserUids + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HasFormUserUids_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_001 start"; + + int64_t formId = 1; + + EXPECT_EQ(false, formDataMgr_.HasFormUserUids(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HasFormUserUids_002 + * @tc.name: HasFormUserUids + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HasFormUserUids_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_002 start"; + + int64_t formId = 2; + + // create formRecords_ + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(true, formDataMgr_.HasFormUserUids(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HasFormUserUids_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetFormHostRecord_001 + * @tc.name: GetFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetFormHostRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_001 start"; + + int64_t formId = 1; + FormHostRecord formHostRecord; + + EXPECT_EQ(false, formDataMgr_.GetFormHostRecord(formId, formHostRecord)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetFormHostRecord_002 + * @tc.name: GetFormHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetFormHostRecord_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_002 start"; + + int64_t formId = 2; + FormHostRecord formHostRecord; + + // create clientRecords_ + FormHostRecord form_host_record; + form_host_record.SetClientStub(token_); + form_host_record.AddForm(formId); + formDataMgr_.clientRecords_.push_back(form_host_record); + + EXPECT_EQ(true, formDataMgr_.GetFormHostRecord(formId, formHostRecord)); + EXPECT_EQ(true, formHostRecord.forms_[formId]); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetFormHostRecord_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_DeleteHostRecord_001 + * @tc.name: DeleteHostRecord + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_DeleteHostRecord_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_DeleteHostRecord_001 start"; + + int64_t formId = 1; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.DeleteHostRecord(token_, formId)); + EXPECT_EQ(true, formDataMgr_.clientRecords_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_DeleteHostRecord_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanHostRemovedForms_001 + * @tc.name: CleanHostRemovedForms + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanHostRemovedForms_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanHostRemovedForms_001 start"; + + std::vector removedFormIds; + int64_t formId = 1; + removedFormIds.emplace_back(formId); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + formDataMgr_.CleanHostRemovedForms(removedFormIds); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanHostRemovedForms_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HandleHostDied_001 + * @tc.name: HandleHostDied + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ & tempForms_ & formRecords is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HandleHostDied_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_001 start"; + + int64_t formId = 1; + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(formId); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.HandleHostDied(token_); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HandleHostDied_002 + * @tc.name: HandleHostDied + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * tempForms_ is not match. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HandleHostDied_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_002 start"; + + int64_t formId = 2; + int64_t otherFormId = 3; + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(otherFormId); + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.HandleHostDied(token_); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_HandleHostDied_003 + * @tc.name: HandleHostDied + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * remoteHost is not match, formRecords is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_HandleHostDied_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_003 start"; + + int64_t formId = 3; + + // create clientRecords_ + sptr token_2; + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_2); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.HandleHostDied(token_); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_HandleHostDied_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_IsEnableRefresh_001 + * @tc.name: IsEnableRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_IsEnableRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_001 start"; + + int64_t formId = 1; + EXPECT_EQ(false, formDataMgr_.IsEnableRefresh(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_IsEnableRefresh_002 + * @tc.name: IsEnableRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_IsEnableRefresh_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_002 start"; + + int64_t formId = 2; + + // create clientRecords_ + sptr token_; + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.IsEnableRefresh(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_IsEnableRefresh_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GenerateUdidHash_001 + * @tc.name: GenerateUdidHash + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * udidHash_ is not 0. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GenerateUdidHash_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_001 start"; + + formDataMgr_.udidHash_ = 1; + EXPECT_EQ(true, formDataMgr_.GenerateUdidHash()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GenerateUdidHash_002 + * @tc.name: GenerateUdidHash + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * udidHash_ is 0. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GenerateUdidHash_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_002 start"; + + formDataMgr_.udidHash_ = Constants::INVALID_UDID_HASH; + EXPECT_EQ(true, formDataMgr_.GenerateUdidHash()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GenerateUdidHash_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetMatchedHostClient_001 + * @tc.name: GetMatchedHostClient + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetMatchedHostClient_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_001 start"; + + // create clientRecords_ + FormHostRecord formHostRecord; + + EXPECT_EQ(false, formDataMgr_.GetMatchedHostClient(token_, formHostRecord)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetMatchedHostClient_002 + * @tc.name: GetMatchedHostClient + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetMatchedHostClient_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_002 start"; + + int64_t formId = 2; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + FormHostRecord formHostRecordOutput; + + EXPECT_EQ(true, formDataMgr_.GetMatchedHostClient(token_, formHostRecordOutput)); + EXPECT_EQ(true, formHostRecordOutput.forms_[formId]); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetMatchedHostClient_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetNeedRefresh_001 + * @tc.name: SetNeedRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetNeedRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_001 start"; + + int64_t formId = 1; + bool needRefresh = true; + + formDataMgr_.SetNeedRefresh(formId, needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetNeedRefresh_002 + * @tc.name: SetNeedRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetNeedRefresh_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_002 start"; + + int64_t formId = 2; + bool needRefresh = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetNeedRefresh(formId, needRefresh); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetNeedRefresh_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetCountTimerRefresh_001 + * @tc.name: SetCountTimerRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetCountTimerRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_001 start"; + + int64_t formId = 1; + bool countTimerRefresh = true; + + formDataMgr_.SetCountTimerRefresh(formId, countTimerRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetCountTimerRefresh_002 + * @tc.name: SetCountTimerRefresh + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetCountTimerRefresh_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_002 start"; + + int64_t formId = 2; + bool countTimerRefresh = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetCountTimerRefresh(formId, countTimerRefresh); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isCountTimerRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetCountTimerRefresh_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetUpdatedForm_001 + * @tc.name: GetUpdatedForm + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * targetForms is empty. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_001 start"; + + FormRecord record; + std::vector targetForms; + FormInfo updatedForm; + + EXPECT_EQ(false, formDataMgr_.GetUpdatedForm(record, targetForms, updatedForm)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetUpdatedForm_002 + * @tc.name: GetUpdatedForm + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * targetForms is not empty. record is same as formInfo. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_002 start"; + + int32_t specification = 2; + + FormRecord record; + record.bundleName = FORM_HOST_BUNDLE_NAME; + record.moduleName = PARAM_PROVIDER_MODULE_NAME; + record.abilityName = FORM_PROVIDER_ABILITY_NAME; + record.formName = FORM_NAME; + record.specification = specification; + + std::vector targetForms; + FormInfo formInfo; + formInfo.bundleName = FORM_HOST_BUNDLE_NAME; + formInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + formInfo.abilityName = FORM_PROVIDER_ABILITY_NAME; + formInfo.name = FORM_NAME; + formInfo.supportDimensions.emplace_back(specification); + targetForms.emplace_back(formInfo); + + FormInfo updatedForm; + + EXPECT_EQ(true, formDataMgr_.GetUpdatedForm(record, targetForms, updatedForm)); + EXPECT_EQ(FORM_HOST_BUNDLE_NAME, updatedForm.bundleName); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetUpdatedForm_003 + * @tc.name: GetUpdatedForm + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * targetForms is not empty. record is not same as formInfo. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_003 start"; + + int32_t specification = 3; + + FormRecord record; + record.bundleName = "bundleName"; + record.moduleName = PARAM_PROVIDER_MODULE_NAME; + record.abilityName = FORM_PROVIDER_ABILITY_NAME; + record.formName = FORM_NAME; + record.specification = specification; + + std::vector targetForms; + FormInfo formInfo; + formInfo.bundleName = FORM_HOST_BUNDLE_NAME; + formInfo.moduleName = PARAM_PROVIDER_MODULE_NAME; + formInfo.abilityName = FORM_PROVIDER_ABILITY_NAME; + formInfo.name = FORM_NAME; + formInfo.supportDimensions.emplace_back(specification); + targetForms.emplace_back(formInfo); + + FormInfo updatedForm; + + EXPECT_EQ(false, formDataMgr_.GetUpdatedForm(record, targetForms, updatedForm)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetEnableUpdate_001 + * @tc.name: SetEnableUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetEnableUpdate_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_001 start"; + + int64_t formId = 1; + bool enableUpdate = true; + + formDataMgr_.SetEnableUpdate(formId, enableUpdate); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetEnableUpdate_002 + * @tc.name: SetEnableUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetEnableUpdate_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_002 start"; + + int64_t formId = 2; + bool enableUpdate = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetEnableUpdate(formId, enableUpdate); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isEnableUpdate); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetEnableUpdate_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetUpdateInfo_001 + * @tc.name: SetUpdateInfo + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetUpdateInfo_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_001 start"; + + int64_t formId = 1; + bool enableUpdate = true; + long updateDuration = 100; + int updateAtHour = 24; + int updateAtMin = 59; + + formDataMgr_.SetUpdateInfo(formId, enableUpdate, updateDuration, updateAtHour, updateAtMin); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetUpdateInfo_002 + * @tc.name: SetUpdateInfo + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetUpdateInfo_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_002 start"; + + int64_t formId = 1; + bool enableUpdate = true; + long updateDuration = 100; + int updateAtHour = 24; + int updateAtMin = 59; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetUpdateInfo(formId, enableUpdate, updateDuration, updateAtHour, updateAtMin); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isEnableUpdate); + EXPECT_EQ(100, formDataMgr_.formRecords_.find(formId)->second.updateDuration); + EXPECT_EQ(24, formDataMgr_.formRecords_.find(formId)->second.updateAtHour); + EXPECT_EQ(59, formDataMgr_.formRecords_.find(formId)->second.updateAtMin); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetUpdateInfo_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedFormRecords_001 + * @tc.name: CleanRemovedFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * removedForm is matched with formRecords_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedFormRecords_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_001 start"; + + // create formRecords + int callingUid = 0; + int64_t formId = 1; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set removedForms; + int64_t removedForm = formId; + removedForms.emplace(removedForm); + + formDataMgr_.CleanRemovedFormRecords(bundleName, removedForms); + EXPECT_EQ(true, formDataMgr_.formRecords_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedFormRecords_002 + * @tc.name: CleanRemovedFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * removedForm is not matched with formRecords_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedFormRecords_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_002 start"; + + // create formRecords + int callingUid = 0; + int64_t formId = 2; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set removedForms; + int64_t removedForm = 100; + removedForms.emplace(removedForm); + + formDataMgr_.CleanRemovedFormRecords(bundleName, removedForms); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedFormRecords_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedTempFormRecords_001 + * @tc.name: CleanRemovedTempFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * bundleName is matched with formRecords_, and it is temp. + * erase formRecords_ and tempForms_. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedTempFormRecords_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_001 start"; + + int64_t formId = 1; + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set removedForms; + int64_t removedForm = formId; + removedForms.emplace(removedForm); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(bundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(formId); + + formDataMgr_.CleanRemovedTempFormRecords(bundleName, removedForms); + EXPECT_EQ(true, formDataMgr_.formRecords_.empty()); + EXPECT_EQ(true, formDataMgr_.tempForms_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_CleanRemovedTempFormRecords_002 + * @tc.name: CleanRemovedTempFormRecords + + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * bundleName is not matched with formRecords_. + * erase none. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CleanRemovedTempFormRecords_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_002 start"; + + int64_t formId = 2; + std::string bundleName = FORM_HOST_BUNDLE_NAME; + std::string otherBundleName = "bundleName"; + + std::set removedForms; + int64_t removedForm = formId; + removedForms.emplace(removedForm); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(otherBundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + // create tempForms_ + formDataMgr_.tempForms_.emplace_back(formId); + + formDataMgr_.CleanRemovedTempFormRecords(bundleName, removedForms); + EXPECT_EQ(false, formDataMgr_.formRecords_.empty()); + EXPECT_EQ(false, formDataMgr_.tempForms_.empty()); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CleanRemovedTempFormRecords_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001 + * @tc.name: GetReCreateFormRecordsByBundleName + + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001 start"; + + int64_t formId = 1; + std::string bundleName = FORM_HOST_BUNDLE_NAME; + + std::set reCreateForms; + int64_t reCreateForm = formId; + reCreateForms.emplace(reCreateForm); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + formItemInfo.SetProviderBundleName(bundleName); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.GetReCreateFormRecordsByBundleName(bundleName, reCreateForms); + EXPECT_EQ(true, reCreateForms.count(formId)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetReCreateFormRecordsByBundleName_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetFormCacheInited_001 + * @tc.name: SetFormCacheInited + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetFormCacheInited_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_001 start"; + + int64_t formId = 1; + + formDataMgr_.SetFormCacheInited(formId, true); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetFormCacheInited_002 + * @tc.name: SetFormCacheInited + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetFormCacheInited_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_002 start"; + + int64_t formId = 2; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetFormCacheInited(formId, true); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.isInited); + EXPECT_EQ(false, formDataMgr_.formRecords_.find(formId)->second.needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetFormCacheInited_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetVersionUpgrade_001 + * @tc.name: SetVersionUpgrade + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is not found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetVersionUpgrade_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_001 start"; + + int64_t formId = 1; + bool version = true; + + formDataMgr_.SetVersionUpgrade(formId, version); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_SetVersionUpgrade_002 + * @tc.name: SetFormCacheInitedTrue + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords_ is found. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetVersionUpgrade_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_002 start"; + + int64_t formId = 2; + bool versionUpgrade = true; + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + formDataMgr_.SetVersionUpgrade(formId, versionUpgrade); + EXPECT_EQ(true, formDataMgr_.formRecords_.find(formId)->second.versionUpgrade); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_SetVersionUpgrade_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostNeedRefresh_001 + * @tc.name: UpdateHostNeedRefresh + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostNeedRefresh_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostNeedRefresh_001 start"; + + int64_t formId = 1; + bool needRefresh = true; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + formDataMgr_.UpdateHostNeedRefresh(formId, needRefresh); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostNeedRefresh_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostForm_001 + * @tc.name: UpdateHostForm + * @tc.desc: Verify that the return value is correct. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostForm_001 start"; + + int64_t formId = 1; + FormRecord formRecord; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(true, formDataMgr_.UpdateHostForm(formId, formRecord)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostForm_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_001 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not exit. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_001 start"; + + std::vector formIds; + int64_t formId = 1; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + EXPECT_EQ(ERR_FORM_INVALID_PARAM, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_001 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_002 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords's VersionUpgrade is false. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_002 start"; + + std::vector formIds; + int64_t formId = 2; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // SetNeedRefresh:true + formHostRecord.SetNeedRefresh(formId, true); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + // versionUpgrade : false + formDataMgr_.SetVersionUpgrade(formId, false); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_002 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_003 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords's VersionUpgrade is true. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_003 start"; + + std::vector formIds; + int64_t formId = 3; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // SetNeedRefresh:true + formHostRecord.SetNeedRefresh(formId, true); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + // versionUpgrade : true + formDataMgr_.SetVersionUpgrade(formId, true); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_003 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_004 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_'s NeedRefresh is false. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_004 start"; + + std::vector formIds; + int64_t formId = 4; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // SetNeedRefresh:false + formHostRecord.SetNeedRefresh(formId, false); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_004 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_005 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * clientRecords_ is not include formId. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_005 start"; + + std::vector formIds; + int64_t formId = 5; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + int64_t otherformId = 500; + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(otherformId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_005 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_006 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * flag is false. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_006 start"; + + std::vector formIds; + int64_t formId = 6; + formIds.emplace_back(formId); + + bool flag = false; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_006 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_007 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords's needRefresh is true. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_007 start"; + + std::vector formIds; + int64_t formId = 7; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + // needRefresh:true + record.needRefresh = true; + formDataMgr_.formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_007 end"; +} + +/** + * @tc.number: FmsFormDataMgrTest_UpdateHostFormFlag_008 + * @tc.name: UpdateHostFormFlag + * @tc.desc: Verify that the return value is correct. + * @tc.details: + * formRecords is not include formId. + */ +HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_008 start"; + + std::vector formIds; + int64_t formId = 8; + formIds.emplace_back(formId); + + bool flag = true; + + std::vector refreshForms; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formDataMgr_.clientRecords_.push_back(formHostRecord); + + // create formRecords + int64_t otherFormId = 800; + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(otherFormId, formItemInfo); + FormRecord record = formDataMgr_.CreateFormRecord(formItemInfo, callingUid); + formDataMgr_.formRecords_.emplace(otherFormId, record); + + EXPECT_EQ(ERR_OK, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + + GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_008 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_db_record_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_db_record_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..22051724cddd4a3f0ed2b4003a9a82044edd5b23 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_db_record_test/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormDbRecordTest") { + module_out_path = module_output_path + + sources = [ "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp" ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + + #"//foundation/appexecfwk/standard/services/bundlemgr/include", + #"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + + #"//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + ] + + configs = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + + #"${libs_path}/libeventhandler:libeventhandler_target", + #"//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormDbRecordTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..944bfb5e83bd889aa6558b0d86698aa4690b2c36 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#define private public +#include "form_db_cache.h" +#include "form_mgr_adapter.h" +#include "form_storage_mgr.h" +#undef private +#include "form_record.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +class FmsFormDbRecordTest : public testing::Test { +public: + void InitFormRecord(); + FormRecord formRecord_; + FormMgrAdapter formMgrAdapter_; +}; + +void FmsFormDbRecordTest::InitFormRecord() +{ + formRecord_.isInited = false; + formRecord_.needFreeInstall = false; + formRecord_.versionUpgrade = false; + formRecord_.needRefresh = false; + formRecord_.packageName = "TestPackageName"; + formRecord_.bundleName = "TestBundleName"; + formRecord_.moduleName = "TestModuleName"; + formRecord_.abilityName = "TestAbilityName"; + formRecord_.formName = "TestFormName"; + formRecord_.specification = 0; + formRecord_.isEnableUpdate = false; + formRecord_.updateDuration = 0; + formRecord_.updateAtHour = 0; + formRecord_.updateAtMin = 0; + formRecord_.hapSourceDirs.emplace_back("hapSourceDirs1"); + formRecord_.formName = "formNameTest"; + formRecord_.formTempFlg = false; + formRecord_.formUserUids.emplace_back(1); + formRecord_.formVisibleNotify = false; + formRecord_.formVisibleNotifyState = 0; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_001, TestSize.Level0) // create +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_001 start"; + FormDbCache::GetInstance().Start(); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_001 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_002, TestSize.Level0) // save formId 0, callIds[1] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_002 start"; + InitFormRecord(); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(0, formRecord_)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_002 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_003, TestSize.Level0) // save formId 1, callIds[1, 0] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_003 start"; + InitFormRecord(); + formRecord_.formUserUids.emplace_back(0); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(1, formRecord_)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_003 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_004, TestSize.Level0) // modify formId 1, callIds[1,2] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_004 start"; + InitFormRecord(); + formRecord_.formUserUids.emplace_back(2); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(1, formRecord_)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_004 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_005, TestSize.Level0) // modify formId 0, callIds[1,2] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_005 start"; + InitFormRecord(); + formRecord_.formUserUids.emplace_back(2); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(0, formRecord_)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_005 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_006, TestSize.Level0) // GetAllDBRecord +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 start"; + FormRecord record; + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(0, record)); + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formUserUids:" << record.formUserUids[j]; + } + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 -------------------"; + + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(1, record)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 formUserUids:" << record.formUserUids[j]; + } + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_006 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_007, TestSize.Level0) // save for next load: formId 0, callIds[1] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 start"; + + InitFormRecord(); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(0, formRecord_)); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_007 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_008, TestSize.Level0) // save for next load: formId 1, callIds[1,0] +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_008 start"; + + InitFormRecord(); + formRecord_.formUserUids.emplace_back(0); + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().UpdateDBRecord(1, formRecord_)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_008 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_009, TestSize.Level0) // GetAllDBRecord +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 start"; + + FormRecord record; + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(0, record)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 formUserUids:" << record.formUserUids[j]; + } + + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 -------------------"; + + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().GetDBRecord(1, record)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 formName: " << record.formName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 bundleName:" << record.bundleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 moduleName:" << record.moduleName; + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 abilityName:" << record.abilityName; + for (unsigned int j = 0; j < record.formUserUids.size(); j++){ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 formUserUids:" << record.formUserUids[j]; + } + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_009 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_010, TestSize.Level0) // DeleteDbRecord(1) +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_010 start"; + EXPECT_EQ(ERR_OK, FormDbCache::GetInstance().DeleteFormInfo(1)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_010 end"; +} + +HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_011, TestSize.Level0) // DeleteDbRecord not exist +{ + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_011 start"; + EXPECT_EQ(ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, FormDbCache::GetInstance().DeleteFormInfo(2)); + GTEST_LOG_(INFO) << "FmsFormDbRecordTest_011 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_host_record_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..8f7fc495b49e59f90b2a875e85a937b0ffe78340 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_host_record_test/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormHostRecordTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_host_record_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormHostRecordTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9956ac308e4695956474ed43298c718fe58ccf0 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2021 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormHostRecordTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormHostRecordTest::SetUpTestCase() +{} + +void FmsFormHostRecordTest::TearDownTestCase() +{} + +void FmsFormHostRecordTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormHostRecordTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormHostRecord + * SubFunction: OnRemoteDied Function + * FunctionPoints: FormMgr OnRemoteDied interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is not 0 after remote died. + */ +HWTEST_F(FmsFormHostRecordTest, OnRemoteDied_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_host_record_test_001 start"; + + int64_t formId1 {12001}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId1); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + int64_t formId2 {12002}; + FormItemInfo record2; + record2.SetFormId(formId2); + record2.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record2.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(record2, callingUid); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId1, callingUid); + + FormHostRecord hostRecord; + FormDataMgr::GetInstance().GetFormHostRecord(formId1, hostRecord); + hostRecord.GetDeathRecipient()->OnRemoteDied(token_); + + FormDataMgr::GetInstance().DeleteFormRecord(formId1); + FormDataMgr::GetInstance().DeleteFormRecord(formId2); + FormDataMgr::GetInstance().ClearHostDataByUId(callingUid); + + GTEST_LOG_(INFO) << "fms_form_host_record_test_001 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..9a2aaf24cf3c451ace5d628b8fbc45fc5b80902a --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/BUILD.gn @@ -0,0 +1,86 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrAddFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_add_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${services_path}/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrAddFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2213089b19d1b04143eb57ade603dfa6790ed8ee --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp @@ -0,0 +1,547 @@ +/* + * Copyright (c) 2021 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#define private public +#include "form_data_mgr.h" +#undef private +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrAddFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrAddFormTest::SetUpTestCase() +{} + +void FmsFormMgrAddFormTest::TearDownTestCase() +{} + +void FmsFormMgrAddFormTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrAddFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke AddForm works. + */ + +HWTEST_F(FmsFormMgrAddFormTest, AddForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_001 start"; + // No cache + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); + token_->Wait(); + + size_t dataCnt{1}; + int64_t formId = formJsInfo.formId; + // Form record alloted. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database info alloted. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // Form host record alloted. + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Add form with cache info. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_002 start"; + + int64_t formId = 0x0ffabcff00000000; + int callingUid {0}; + // Set cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetModuleName(PARAM_FORM_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + retFormRec.updateAtHour = 1; + retFormRec.updateAtMin = 1; + FormDataMgr::GetInstance().UpdateFormRecord(formId, retFormRec); + // Set database info + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + GTEST_LOG_(INFO) << "formId :"<Wait(); + + size_t dataCnt{1}; + size_t formUserUidCnt{1}; + // Cache params updated. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(formUserUidCnt, formInfo.formUserUids.size()); + // database info updated. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(formUserUidCnt, dbInfo.formUserUids.size()); + // Form host record not changed. + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_002 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Add form with database info but without cache. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_003 start"; + + int64_t formId = 0x0ffabcdf00000000; + int callingUid {0}; + // Set database info + FormRecord record1; + record1.formId = formId; + record1.bundleName = FORM_PROVIDER_BUNDLE_NAME; + record1.moduleName = PARAM_FORM_NAME; + record1.abilityName = FORM_PROVIDER_ABILITY_NAME; + record1.formName = PARAM_FORM_NAME; + record1.specification = PARAM_FORM_DIMENSION_VALUE; + record1.formUserUids.emplace_back(callingUid); + record1.formTempFlg = false; + FormDBInfo formDBInfo(formId, record1); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + GTEST_LOG_(INFO) << "formId :"<Wait(); + + size_t dataCnt{1}; + size_t formUserUidCnt{1}; + // Cache params updated. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(formUserUidCnt, formInfo.formUserUids.size()); + // databse info updated. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(formUserUidCnt, dbInfo.formUserUids.size()); + // Form host record not changed. + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Invalid case when callertoken is nullptr. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_004 start"; + + int64_t formId = 0x0ffabcde00000000; + + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: BundleName,AbilityName,moduleName in Want is null separately. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_005 start"; + + int64_t formId = 0x0ffabcdd00000000; + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, "", FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, ""); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + std::string tmp = ""; + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, tmp); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().AddForm(formId, want, nullptr, formJsInfo)); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_005 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case when cache info is not matched with form. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_006 start"; + + int64_t formId = 0x0ababcff00000000; + int callingUid {0}; + // Set cache info . + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_ABILITY_NAME); + record1.SetModuleName(PARAM_FORM_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record. + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, 111L, callingUid); + + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false); + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + GTEST_LOG_(INFO) << "formId :"<Wait(); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_006 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: AddForm Function + * FunctionPoints: FormMgr AddForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case when temp form is out of limit. + */ +HWTEST_F(FmsFormMgrAddFormTest, AddForm_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_add_form_test_007 start"; + + int64_t formId = 0x0ababc5f00000000; + int callingUid {0}, tempCount = 0; + // Set cache info . + FormItemInfo record1[OHOS::AppExecFwk::Constants::MAX_TEMP_FORMS]; + for (; tempCountWait(); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + for (tempCount = 0; tempCountWait(); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + for (tempCount = 0; tempCount +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrCastTempFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrCastTempFormTest::SetUpTestCase() +{} + +void FmsFormMgrCastTempFormTest::TearDownTestCase() +{} + +void FmsFormMgrCastTempFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrCastTempFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke CastTempForm works. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_001 start"; + + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + int callingUid {1}; + // cache info + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetModuleName(PARAM_FORM_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(true); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // host object + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + ASSERT_EQ(ERR_OK, FormMgr::GetInstance().CastTempForm(formId, token_)); + token_->Wait(); + + size_t dataCnt {1}; + // form record is updated + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t userUidCnt {2}; + EXPECT_EQ(userUidCnt, formInfo.formUserUids.size()); + // db data is added + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(userUidCnt, dbInfo.formUserUids.size()); + // host is added + FormHostRecord hostRecord; + ret = FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord); + EXPECT_TRUE(ret); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: form id <= 0 or Caller ability token is nullptr. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 start"; + // form id <= 0 + ASSERT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(0L, token_)); + // Caller ability token is nullptr + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + ASSERT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(formId, nullptr)); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Temp form is not in form cache. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 start"; + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + // form is not exist in cache + ASSERT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().CastTempForm(formId, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: CastTempForm Function + * FunctionPoints: FormMgr CastTempForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Temp form is not in host. + */ +HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_004 start"; + + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + int callingUid {1}; + // cache data + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetModuleName(PARAM_FORM_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetFormName(PARAM_FORM_NAME); + record1.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record1.SetTemporaryFlag(true); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + + ASSERT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().CastTempForm(formId, token_)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_004 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..35100ba0d244e7404d6d8cfe235cb58d3ff9f8a3 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn @@ -0,0 +1,17 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e18f830ad221d64bba3116b69eb3a62c66945d62 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2021 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#define private public +#include "form_data_mgr.h" +#undef private +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_death_callback.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrDeathCallbackTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrDeathCallbackTest::SetUpTestCase() +{} + +void FmsFormMgrDeathCallbackTest::TearDownTestCase() +{} + +void FmsFormMgrDeathCallbackTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrDeathCallbackTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr::FormMgrDeathRecipient + * SubFunction: OnRemoteDied Function + * FunctionPoints: FormMgr::FormMgrDeathRecipient OnRemoteDied interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr::FormMgrDeathRecipient invoke OnRemoteDied works. + */ +HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_001 start"; + // No cache + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME) + .SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME) + .SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE) + .SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false) + .SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); + token_->Wait(); + + std::shared_ptr deathCallback = std::make_shared(); + FormMgr::GetInstance().RegisterDeathCallback(deathCallback); + EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); + FormMgr::GetInstance().GetDeathRecipient()->OnRemoteDied(formyMgrServ_->AsObject()); + + int64_t formId = formJsInfo.formId; + + FormHostRecord hostRecord; + EXPECT_EQ(true, FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + EXPECT_EQ(true, token_->AsObject() == hostRecord.clientStub_); + EXPECT_EQ(true, FormMgr::GetRecoverStatus() == Constants::NOT_IN_RECOVERY); + + FormMgr::GetInstance().UnRegisterDeathCallback(deathCallback); + EXPECT_EQ(false, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr::FormMgrDeathRecipient + * SubFunction: OnRemoteDied Function + * FunctionPoints: FormMgr::FormMgrDeathRecipient OnRemoteDied interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr::FormMgrDeathRecipient invoke OnRemoteDied works when remote is nullptr. + */ +HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_002 start"; + // No cache + FormJsInfo formJsInfo; + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME) + .SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME) + .SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME) + .SetParam(Constants::PARAM_FORM_DIMENSION_KEY, PARAM_FORM_DIMENSION_VALUE) + .SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME) + .SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, false) + .SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); + token_->Wait(); + + std::shared_ptr deathCallback = std::make_shared(); + FormMgr::GetInstance().RegisterDeathCallback(deathCallback); + EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); + + int beforeRecoverStatus = FormMgr::GetRecoverStatus(); + FormMgr::GetInstance().GetDeathRecipient()->OnRemoteDied(nullptr); + EXPECT_EQ(true, FormMgr::GetRecoverStatus() == beforeRecoverStatus); + + int64_t formId = formJsInfo.formId; + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + + GTEST_LOG_(INFO) << "fms_form_mgr_death_callback_test_002 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e20b99a0fa1fd5fbfcc1e53ad469f7a10dd7e156 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/BUILD.gn @@ -0,0 +1,86 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrDeleteFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_delete_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${services_path}/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrDeleteFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05bc3c5e86740b4ee912dabe79d48c6e566be4ba --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp @@ -0,0 +1,465 @@ +/* + * Copyright (c) 2021 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrDeleteFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrDeleteFormTest::SetUpTestCase() +{} + +void FmsFormMgrDeleteFormTest::TearDownTestCase() +{} + +void FmsFormMgrDeleteFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrDeleteFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is not 0 after delete form. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_001 start"; + + int64_t formId {12001}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + int formUserUid {1}; + FormDataMgr::GetInstance().AddFormUserUid(formId, formUserUid); + // Set form host record + retFormRec.formUserUids.emplace_back(formUserUid); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().DeleteForm(formId, token_)); + token_->Wait(); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t dataCnt{1}; + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // Form host record is deleted. + FormHostRecord hostRecord; + EXPECT_FALSE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is 0 after delete form. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_002 start"; + + int64_t formId {12002}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().DeleteForm(formId, token_)); + token_->Wait(); + + // Cache uid is deleted. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_FALSE(ret); + // Database is deleted. + size_t dataCnt{0}; + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + // Form host record is deleted. + FormHostRecord hostRecord; + EXPECT_FALSE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Test cases when some paraments are invalid + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 start"; + // case when formId<=0 + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(0, token_)); + // case when token is nullptr + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(123L, nullptr)); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if check permission error. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_004 start"; + int64_t formId {12004}; + // Remove Permission + OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); + OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, 0); + OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().DeleteForm(formId, token_)); + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Cases when permission is not available + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_005 start"; + int64_t formId {12005}; + int callingUid {0}; + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName("ERR BUNDLE NAME"); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().DeleteForm(formId, token_)); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_005 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case with no database info and form is not temporary. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_006 start"; + + int64_t formId {12006}; + int callingUid {0}; + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().DeleteForm(formId, token_)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_006 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Case when form with database info, not temporary form, without host record. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_007 start"; + + int64_t formId {12007}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + retFormRec.formUserUids.clear(); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + ASSERT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().DeleteForm(formId, token_)); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t dataCnt{1}; + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + dataCnt = 0; + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // Form host record is not deleted. + FormHostRecord hostRecord; + EXPECT_TRUE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_007 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: DeleteForm Function + * FunctionPoints: FormMgr DeleteForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Persistent data,abilityName or bundleName is empty. + */ +HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_008 start"; + + int64_t formId {12008}; + int callingUid {0}; + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(""); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + ASSERT_EQ(ERR_CODE_COMMON, FormMgr::GetInstance().DeleteForm(formId, token_)); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + size_t dataCnt{1}; + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + std::vector formDBInfos; + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + FormDBInfo dbInfo {formDBInfos[0]}; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // form host record is not deleted yet. + FormHostRecord hostRecord; + EXPECT_TRUE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + // Database info. + FormDbCache::GetInstance().DeleteFormInfo(formId); + retFormRec.bundleName = ""; + retFormRec.abilityName = FORM_PROVIDER_ABILITY_NAME; + FormDBInfo formDBInfo1(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo1); + + EXPECT_EQ(ERR_CODE_COMMON, FormMgr::GetInstance().DeleteForm(formId, token_)); + + // Cache uid is not deleted yet. + ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_TRUE(ret); + EXPECT_EQ(dataCnt, formInfo.formUserUids.size()); + // Database is not deleted yet. + formDBInfos.clear(); + FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); + EXPECT_EQ(dataCnt, formDBInfos.size()); + dbInfo = formDBInfos[0]; + EXPECT_EQ(formId, dbInfo.formId); + EXPECT_EQ(dataCnt, dbInfo.formUserUids.size()); + // form host record is not deleted yet. + EXPECT_TRUE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_008 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3ea0a927c2a0ba6914c8f62602cacbf04e05004e --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/BUILD.gn @@ -0,0 +1,88 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrLifecycleUpdateTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", + ] + + configs = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + + #"${libs_path}/libeventhandler:libeventhandler_target", + #"//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrLifecycleUpdateTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86deffae18a98f1e43868560cafd5a2d08a85f1d --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2021 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 "form_bms_helper.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#include "form_mgr_service.h" +#include "form_data_mgr.h" +#undef private +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test"; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; + +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrLifecycleUpdateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + void InitFormItemInfo(int64_t formId, FormItemInfo &formItemInfo) const; + +protected: + sptr mockBundleMgr_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + sptr token_; +}; + +void FmsFormMgrLifecycleUpdateTest::SetUpTestCase() +{} + +void FmsFormMgrLifecycleUpdateTest::TearDownTestCase() +{} + +void FmsFormMgrLifecycleUpdateTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_enable_update_test_001 setup"); + formyMgrServ_->OnStart(); + + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + // token + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrLifecycleUpdateTest::TearDown() +{} + +void FmsFormMgrLifecycleUpdateTest::InitFormItemInfo(int64_t formId, FormItemInfo &formItemInfo) const +{ + // create hapSourceDirs + std::vector hapSourceDirs; + std::string hapSourceDir = "1/2/3"; + hapSourceDirs.emplace_back(hapSourceDir); + + // create formItemInfo + formItemInfo.SetFormId(formId); + formItemInfo.SetTemporaryFlag(true); + formItemInfo.SetEnableUpdateFlag(true); + formItemInfo.SetUpdateDuration(Constants::MIN_CONFIG_DURATION); + formItemInfo.SetScheduledUpdateTime("10:30"); + formItemInfo.SetHapSourceDirs(hapSourceDirs); +} +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_001 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: permission denied. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_001 start"; + + std::vector formIds; + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + // Remove Permission + OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); + OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, 0); + OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_001 end"; +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: formIds is empty. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 start"; + + std::vector formIds; + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 end"; +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: clientRecords_ is empty. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 start"; + + std::vector formIds; + formIds.push_back(3); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 end"; +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: + * clientRecords_ is exist, but no formRecords. + * set EnableRefresh, and not pull up Provider. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004 start"; + + std::vector formIds; + int64_t formId = 4; + formIds.push_back(formId); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formHostRecord.SetNeedRefresh(formId, true); + FormDataMgr::GetInstance().clientRecords_.push_back(formHostRecord); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_004 end"; +} + + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * @tc.info: + * clientRecords and formRecords(needRefresh:true) is exist. + * set EnableRefresh, and pull up Provider and update. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005 start"; + + std::vector formIds; + int64_t formId = 5; + formIds.push_back(formId); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + formHostRecord.SetNeedRefresh(formId, true); + FormDataMgr::GetInstance().clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = FormDataMgr::GetInstance().CreateFormRecord(formItemInfo, callingUid); + // needRefresh:true + record.needRefresh = true; + FormDataMgr::GetInstance().formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_005 end"; +} + +/** + * @tc.number: FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006 + * @tc.name: LifecycleUpdate + * @tc.desc: Verify that the return value is correct. + * + * @tc.info: + * clientRecords(needRefresh:true) and formRecords(needRefresh & versionUpgrade:false) is exist. + * set EnableRefresh, and update hostRecord. + */ +HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006 start"; + + std::vector formIds; + int64_t formId = 6; + formIds.push_back(formId); + + int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; + + // create clientRecords_ + FormHostRecord formHostRecord; + formHostRecord.SetClientStub(token_); + formHostRecord.AddForm(formId); + // needRefresh:true + formHostRecord.SetNeedRefresh(formId, true); + FormDataMgr::GetInstance().clientRecords_.push_back(formHostRecord); + + // create formRecords + int callingUid = 0; + FormItemInfo formItemInfo; + InitFormItemInfo(formId, formItemInfo); + FormRecord record = FormDataMgr::GetInstance().CreateFormRecord(formItemInfo, callingUid); + // needRefresh:false + record.needRefresh = false; + // versionUpgrade:false + record.versionUpgrade = false; + FormDataMgr::GetInstance().formRecords_.emplace(formId, record); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + + // judge hostrecord's needRefresh_ is false. + EXPECT_EQ(false, FormDataMgr::GetInstance().clientRecords_.at(0).IsNeedRefresh(formId)); + + GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_006 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0301957804ed57feb5371510562ddc4e973993ea --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/BUILD.gn @@ -0,0 +1,86 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrMessageEventTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_message_event_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${services_path}/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrMessageEventTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12d4e8395f8bd64594bc64db8d987c258e4531e6 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2021 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission.h" +#include "permission/permission_kit.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +const std::string FORM_MESSAGE_EVENT_VALUE_1 = "event message1"; + +class FmsFormMgrMessageEventTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrMessageEventTest::SetUpTestCase() +{} + +void FmsFormMgrMessageEventTest::TearDownTestCase() +{} + +void FmsFormMgrMessageEventTest::SetUp() +{ + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrMessageEventTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke MessageEvent works. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_001 start"; + + int64_t formId {10000001}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + int formUserUid {1}; + FormDataMgr::GetInstance().AddFormUserUid(formId, formUserUid); + // Set form host record + retFormRec.formUserUids.emplace_back(formUserUid); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if check permission error. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_002 start"; + int64_t formId {10000001}; + // Remove Permission + OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); + OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, 0); + OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME); + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_002 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if formId == 0. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_003 start"; + int64_t formId = 0; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_003 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if callerToken == nullptr. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_004 start"; + int64_t formId {10000001}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().MessageEvent(formId, want, nullptr)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_004 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if message info is not exist. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_005 start"; + int64_t formId {10000001}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_005 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if not exist such form. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_006 start"; + int64_t formId {11100002}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_006 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if cannot find target client. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_007 start"; + int64_t formId {10000001}; + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, FormMgr::GetInstance().MessageEvent(formId, want, + new (std::nothrow) MockFormHostClient())); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_007 end"; +} +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: MessageEvent Function + * FunctionPoints: FormMgr MessageEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if form is not self-owned. + */ +HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_008 start"; + int64_t formId2 {10000001}; + int64_t formId {10000002}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // User Uid Add some Useruids into a form in cache + int formUserUid {1}; + FormDataMgr::GetInstance().AddFormUserUid(formId, formUserUid); + // Set form host record + retFormRec.formUserUids.emplace_back(formUserUid); + FormDBInfo formDBInfo(formId, retFormRec); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId2); + + Want want; + want.SetParam(Constants::PARAM_FORM_HOST_BUNDLENAME_KEY, FORM_HOST_BUNDLE_NAME); + want.SetParam(Constants::PARAM_MODULE_NAME_KEY, PARAM_PROVIDER_MODULE_NAME); + want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); + want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); + want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().MessageEvent(formId2, want, token_)); + GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_008 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f35b3b3e96868aafd6601ebfcf1f75e7c236e25d --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/BUILD.gn @@ -0,0 +1,88 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrNotifyInvisibleFormsTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", + ] + + configs = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + + #"${libs_path}/libeventhandler:libeventhandler_target", + #"//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrNotifyInvisibleFormsTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1d1d1d1dc3a954c39eaff20cf20e2da71659687 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#define private public +#include "form_bms_helper.h" +#include "form_mgr_service.h" +#include "form_mgr_adapter.h" +#include "form_data_mgr.h" +#include "form_mgr.h" +#undef private +#include "form_constants.h" +#include "mock_form_host_client.h" +#include "mock_bundle_manager.h" +#include "permission/permission_def.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string FORM_HOST_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrNotifyInvisibleFormsTest : public testing::Test { +public: + FmsFormMgrNotifyInvisibleFormsTest() : formMgrService_(nullptr) + {} + ~FmsFormMgrNotifyInvisibleFormsTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +protected: + sptr token_; + sptr mockBundleMgr_; + std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); +}; +void FmsFormMgrNotifyInvisibleFormsTest::SetUpTestCase(void) +{} + +void FmsFormMgrNotifyInvisibleFormsTest::TearDownTestCase(void) +{} + +void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) +{ + formMgrService_ = std::make_shared(); + + formMgrService_->OnStart(); + + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + // token + token_ = new (std::nothrow) OHOS::AppExecFwk::MockFormHostClient(); + + // Permission install + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_HOST_BUNDLE_NAME; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_HOST_BUNDLE_NAME, + PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrNotifyInvisibleFormsTest::TearDown(void) +{} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_001 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_APPEXECFWK_FORM_PERMISSION_DENY. + * @tc.info: permission denied. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_001, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_001 start"; + + int64_t formId = 1; + std::vector formIds; + formIds.push_back(formId); + + // Remove Permission + OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_HOST_BUNDLE_NAME); + OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, 0); + OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_HOST_BUNDLE_NAME); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, + token_, Constants::FORM_INVISIBLE )); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_001 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_APPEXECFWK_FORM_INVALID_PARAM. + * @tc.info: callerToken is nullptr. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 start"; + + int64_t formId = 2; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // clear callerToken + token_ = nullptr; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, + token_, Constants::FORM_INVISIBLE )); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: form record is not found. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 start"; + + int64_t formId = 3; + std::vector formIds; + formIds.push_back(formId); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: host form record is not found. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 start"; + + int64_t formId = 4; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: host form record is found, but formVisibleNotify is false. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 start"; + + int64_t formId = 5; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.formVisibleNotify_ = false; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // creat clientRecords_ + FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: host form record is found, formVisibleNotify is true, it is a SystemApp. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 start"; + + int64_t formId = 6; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.formVisibleNotify_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // creat clientRecords_ + FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 + * @tc.name: NotifyInvisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: it is not a SystemApp. + */ +HWTEST_F(FmsFormMgrNotifyInvisibleFormsTest, FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007, +TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 start"; + + int64_t formId = 7; + std::string mockBundleName = "com.form.host.app600"; + std::vector formIds; + formIds.push_back(formId); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = mockBundleName; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + iteminfo.formVisibleNotify_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // creat clientRecords_ + FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); + + // Permission install (mockBundleName) + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = mockBundleName; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(mockBundleName, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(mockBundleName, + PERMISSION_NAME_REQUIRE_FORM, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..82f7bb282004eaa3a193daf38e66f8edf8725efc --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/BUILD.gn @@ -0,0 +1,88 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrNotifyVisibleFormsTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//base/global/resmgr_standard/interfaces/innerkits/include", + ] + + configs = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + + #"${libs_path}/libeventhandler:libeventhandler_target", + #"//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrNotifyVisibleFormsTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83f9d5a58807d54af200400610d38512280aacf6 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#define private public +#include "form_bms_helper.h" +#include "form_constants.h" +#include "form_mgr_service.h" +#include "form_mgr_adapter.h" +#include "form_data_mgr.h" +#include "form_mgr.h" +#undef private +#include "mock_form_host_client.h" +#include "mock_bundle_manager.h" +#include "permission/permission_def.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string NON_SYSTEM_APP_BUNDLE_NAME = "com.form.host.app600"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrNotifyVisibleFormsTest : public testing::Test { +public: + FmsFormMgrNotifyVisibleFormsTest() : formMgrService_(nullptr) + {} + ~FmsFormMgrNotifyVisibleFormsTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +protected: + sptr token_; + sptr mockBundleMgr_; + std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); +}; +void FmsFormMgrNotifyVisibleFormsTest::SetUpTestCase(void) +{} + +void FmsFormMgrNotifyVisibleFormsTest::TearDownTestCase(void) +{} + +void FmsFormMgrNotifyVisibleFormsTest::SetUp(void) +{ + formMgrService_ = std::make_shared(); + formMgrService_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, + PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrNotifyVisibleFormsTest::TearDown(void) +{} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_001 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return code is ERR_APPEXECFWK_FORM_PERMISSION_DENY. + * @tc.info: The permission denied occurred. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_001 start"; + + std::vector formIds; + formIds.push_back(100); + + // Remove permission. + OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); + OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, 0); + OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, + Constants::FORM_VISIBLE)); + + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_001 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return code is ERR_APPEXECFWK_FORM_INVALID_PARAM. + * @tc.info: The callerToken is nullptr. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002 start"; + + // set the callerToken to nullptr. + token_ = nullptr; + + // create formIds + int64_t formId1 = 301; + int64_t formId2 = 302; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + + FormItemInfo formiteminfo2; + formiteminfo2.SetFormId(formId2); + formiteminfo2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo2, 0); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, + Constants::FORM_VISIBLE)); + + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_002 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: Create two formId and push formIds, but only create one form record. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003 start"; + + // create formIds + int64_t formId1 = 401; + int64_t formId2 = 402; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId1, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId1, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_003 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: Create two formId and push formIds, but only create one form host record. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004 start"; + + // create formIds + int64_t formId1 = 501; + int64_t formId2 = 502; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId1, true); + + FormItemInfo formiteminfo2; + formiteminfo2.SetFormId(formId2); + formiteminfo2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo2.SetFormVisibleNotify(true); + formiteminfo2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo2, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId2, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId1, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_004 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: Create two formId and push formIds, two form records and two form host records. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005 start"; + + // create formIds + int64_t formId1 = 601; + int64_t formId2 = 602; + std::vector formIds; + formIds.push_back(formId1); + formIds.push_back(formId2); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId1); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId1, true); + + FormItemInfo formiteminfo2; + formiteminfo2.SetFormId(formId2); + formiteminfo2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo2.SetFormVisibleNotify(true); + formiteminfo2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo2, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId2, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId1, 0); + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo2, token_, formId2, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_005 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: The NeedRefresh is false. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006 start"; + + // create formIds + int64_t formId = 700; + std::vector formIds; + formIds.push_back(formId); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId, false); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_006 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: The FormVisibleNotify is false. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007 start"; + + // create formIds + int64_t formId = 800; + std::vector formIds; + formIds.push_back(formId); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId); + formiteminfo1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(false); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_007 end"; +} + +/** + * @tc.number: FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008 + * @tc.name: NotifyVisibleForms + * @tc.desc: Verify that the return value is ERR_OK. + * @tc.info: The form provider is not a system app. + */ +HWTEST_F(FmsFormMgrNotifyVisibleFormsTest, FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008 start"; + + // create formIds + int64_t formId = 900; + std::vector formIds; + formIds.push_back(formId); + + // create formRecords + FormItemInfo formiteminfo1; + formiteminfo1.SetFormId(formId); + formiteminfo1.SetProviderBundleName(NON_SYSTEM_APP_BUNDLE_NAME); + formiteminfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formiteminfo1.SetFormVisibleNotify(true); + formiteminfo1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formiteminfo1, 0); + FormDataMgr::GetInstance().SetNeedRefresh(formId, true); + + // create formHostRecord + FormDataMgr::GetInstance().AllotFormHostRecord(formiteminfo1, token_, formId, 0); + + // Permission install + std::vector permList; + OHOS::Security::Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = NON_SYSTEM_APP_BUNDLE_NAME; + permDef.grantMode = OHOS::Security::Permission::GrantMode::USER_GRANT; + permDef.availableScope = OHOS::Security::Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(NON_SYSTEM_APP_BUNDLE_NAME, + {PERMISSION_NAME_REQUIRE_FORM}, 0); + OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(NON_SYSTEM_APP_BUNDLE_NAME, + PERMISSION_NAME_REQUIRE_FORM, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_VISIBLE)); + GTEST_LOG_(INFO) << "FmsFormMgrNotifyVisibleFormsTest_NotifyVisibleForms_008 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6eead96a0b2e96687f2cf42495ecb8cf421c56ed --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrReleaseFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_release_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/bundlemgr/test:bundlemgr_test_config", + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrReleaseFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ec263f000f801931dec8394a2b587445ca34c94 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "form_bms_helper.h" +#include "form_cache_mgr.h" +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_db_info.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "mock_bundle_manager.h" +#include "mock_form_token.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test"; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; + +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrReleaseFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + sptr mockBundleMgr_; +}; + +void FmsFormMgrReleaseFormTest::SetUpTestCase() +{} + +void FmsFormMgrReleaseFormTest::TearDownTestCase() +{} + +void FmsFormMgrReleaseFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrReleaseFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is not 0 after release form. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_001 start"; + + int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); + + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record1, 0); + int64_t formId2 = FormDataMgr::GetInstance().GenerateFormId(); + FormItemInfo record2; + record2.SetFormId(formId2); + record2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record2, 1); + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, 0); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + + // Cache uid is not deleted yet. + FormRecord formInfo; + bool ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); + EXPECT_FALSE(ret); + ret = FormDataMgr::GetInstance().GetFormRecord(formId2, formInfo); + EXPECT_TRUE(ret); + // Form host record is deleted. + FormHostRecord hostRecord; + EXPECT_FALSE(FormDataMgr::GetInstance().GetFormHostRecord(formId, hostRecord)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteFormRecord(formId2); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId2); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId2); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Quote of form is 0 after delete form. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_002 start"; + + int64_t formId1 = FormDataMgr::GetInstance().GenerateFormId(); + int64_t formId2 = FormDataMgr::GetInstance().GenerateFormId(); + FormItemInfo record1; + record1.SetFormId(formId1); + record1.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record1, 0); + + FormItemInfo record2; + record2.SetFormId(formId2); + record2.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record2.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record2.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record2, 0); + + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId1, 0); + + FormCacheMgr::GetInstance().AddData(formId1, "test data 1"); + FormCacheMgr::GetInstance().AddData(formId2, "test data 2"); + + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().ReleaseForm(formId1, token_, true)); + + FormDataMgr::GetInstance().DeleteFormRecord(formId1); + FormDataMgr::GetInstance().DeleteFormRecord(formId2); + FormDbCache::GetInstance().DeleteFormInfo(formId1); + FormDbCache::GetInstance().DeleteFormInfo(formId2); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId1); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if check error. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_003 start"; + int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); + // formId<=0 + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(0L, token_, false)); + // sptr is nullptr + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(formId, nullptr, false)); + + // Remove Permission + OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); + OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, 0); + OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().ReleaseForm(formId, token_, false)); + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if formId is not exist in cache. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 start"; + int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); + EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: ReleaseForm Function + * FunctionPoints: FormMgr ReleaseForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: An exception tests if formId is not exist in host. + */ +HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_005 start"; + int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(record, 0); + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + GTEST_LOG_(INFO) << "fms_form_mgr_release_test_005 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cf85c44057c189b699cca2ccf2efe9a6dc812e3c --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/BUILD.gn @@ -0,0 +1,81 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrRequestFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_request_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/bundlemgr/test:bundlemgr_test_config", + "${services_path}/formmgr/test:formmgr_test_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrRequestFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6d4824741384a3c12eddad993ff143dc248d1d6 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "form_data_mgr.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "mock_bundle_manager.h" +#include "mock_ability_manager.h" +#include "system_ability_definition.h" +#include "../../mock/include/mock_form_token.h" +#include "../../mock/include/mock_form_host_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test"; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; + +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrRequestFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr mockAbilityMgrServ_; + sptr mockBundleMgr_; + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); +}; + +void FmsFormMgrRequestFormTest::SetUpTestCase() +{} + +void FmsFormMgrRequestFormTest::TearDownTestCase() +{} + +void FmsFormMgrRequestFormTest::SetUp() +{ + formyMgrServ_->OnStart(); + + token_ = new (std::nothrow) MockFormHostClient(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrRequestFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgrClient + * SubFunction: RequestForm Function + * FunctionPoints: FormMgrClient RequestForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Nomal case: Verify if FormMgrClient invoke RequestForm works. + */ +HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_001, TestSize.Level0) +{ + APP_LOGI("fms_form_mgr_request_test_001 start"); + + int64_t formId {0X0000FFFF00000000}; + int callingUid {0}; + // Create cache + FormItemInfo record1; + record1.SetFormId(formId); + record1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + record1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record1.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); + // Set database info. + retFormRec.formUserUids.clear(); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + Want want; + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().RequestForm(formId, token_, want)); + + token_->Wait(); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + APP_LOGI("fms_form_mgr_request_test_001 end"); +} + +/* + * Feature: FormMgrService + * Function: FormMgrClient + * SubFunction: RequestForm Function + * FunctionPoints: FormMgrClient RequestForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Abnomal case: Verify permission deny. + */ +HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_002, TestSize.Level0) +{ + APP_LOGI("fms_form_mgr_request_test_002 start"); + + int64_t formId {0X0000FFAF00000000}; + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, 0); + + Want want; + OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); + OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, 0); + OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().RequestForm(formId, token_, want)); + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); + token_->Wait(); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + APP_LOGI("fms_form_mgr_request_test_002 end"); +} + +/* + * Feature: FormMgrService + * Function: FormMgrClient + * SubFunction: RequestForm Function + * FunctionPoints: FormMgrClient RequestForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Abnomal case: Verify invalid parameter. + */ +HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_003, TestSize.Level0) +{ + APP_LOGI("fms_form_mgr_request_test_003 start"); + + int64_t formId {0X00AAAAFF00000000}; + FormItemInfo record; + int callingUid {0}; + record.SetFormId(formId); + record.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + + Want want; + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().RequestForm(formId, token_, want)); + + token_->Wait(); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + APP_LOGI("fms_form_mgr_request_test_003 end"); +} + +/* + * Feature: FormMgrService + * Function: FormMgrClient + * SubFunction: RequestForm Function + * FunctionPoints: FormMgrClient RequestForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Abnomal case: Verify form not self. + */ +HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_004, TestSize.Level0) +{ + APP_LOGI("fms_form_mgr_request_test_004 start"); + int64_t formId {0X000ABCFF00000000}; + int64_t fakeFormId {0X0ABCDEFF00000000}; + FormItemInfo record; + int callingUid {0}; + record.SetFormId(formId); + record.SetProviderBundleName(FORM_PROVIDER_BUNDLE_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetTemporaryFlag(false); + FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, fakeFormId, 0); + + Want want; + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().RequestForm(formId, token_, want)); + + token_->Wait(); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + APP_LOGI("fms_form_mgr_request_test_004 end"); +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..372c883790a41ed1546df845ffc9b2af6830458f --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/BUILD.gn @@ -0,0 +1,86 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormMgrUpdateFormTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_update_form_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${services_path}/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormMgrUpdateFormTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f051fc1b05a2f63a58dd0b69a24de67774c3167 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2021 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 "form_ams_helper.h" +#include "form_bms_helper.h" +#include "form_data_mgr.h" +#include "form_host_interface.h" +#define private public +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormMgrUpdateFormTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormMgrUpdateFormTest::SetUpTestCase() +{} + +void FmsFormMgrUpdateFormTest::TearDownTestCase() +{} + +void FmsFormMgrUpdateFormTest::SetUp() +{ + APP_LOGI("fms_form_mgr_client_updateForm_test_001 setup"); + + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormMgrUpdateFormTest::TearDown() +{} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_001 start"; + + // param editor + int64_t formId {100L}; + int32_t callingUid {0}; + std::string bandleName = FORM_HOST_BUNDLE_NAME; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing001\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + FormItemInfo formItemInfo1; + formItemInfo1.SetFormId(1000L); + formItemInfo1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo1.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo1, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + token_->Wait(); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when permission denied. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_002 start"; + + // param editor + int64_t formId {200L}; + int32_t callingUid {0}; + std::string bandleName = FORM_HOST_BUNDLE_NAME; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing002\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // del permission + Permission::PermissionKit::RevokeUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, + callingUid); + + // test exec + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().UpdateForm(formId, bandleName, + formProviderData)); + + // add permission + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, + callingUid); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when passing bandleName is empty. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_003 start"; + + // param editor + int64_t formId {300L}; + int32_t callingUid {0}; + std::string bandleName = ""; + FormProviderData formProviderData; + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when bandleName not match. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_004 start"; + + // param editor + int64_t formId {400L}; + int32_t callingUid {0}; + std::string bandleName = FORM_PROVIDER_BUNDLE_NAME; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing004\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when not under current user. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_005 start"; + + // param editor + int64_t formId {500L}; + int32_t callingUid {1}; + std::string bandleName = FORM_HOST_BUNDLE_NAME; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing005\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_005 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works when the updated form is not your own. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_006 start"; + + // param editor + int64_t formId {600L}; + int32_t callingUid {0}; + std::string bandleName = "com.form.host.app600"; + FormProviderData formProviderData = FormProviderData(std::string("{\"city\": \"beijing006\"}")); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_006 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: UpdateForm Function + * FunctionPoints: FormMgr UpdateForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if FormMgr invoke UpdateForm works. + */ +HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_007 start"; + + // param editor + int64_t formId {700L}; + int32_t callingUid {0}; + std::string bandleName = FORM_HOST_BUNDLE_NAME; + std::string jsonData = std::string("{"); + for (int i = 0; i < 1024; i = i + 1) { + jsonData = jsonData + std::string("\"city" + std::to_string(i) + "\"" + ":" + "\"beijing007\""); + if (i != 1023) { + jsonData = jsonData + std::string(", "); + } + } + jsonData = jsonData + std::string("}"); + FormProviderData formProviderData = FormProviderData(jsonData); + + // add formRecord + FormItemInfo formItemInfo; + formItemInfo.SetFormId(formId); + formItemInfo.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo.SetTemporaryFlag(false); + FormRecord formRecord = FormDataMgr::GetInstance().AllotFormRecord(formItemInfo, callingUid); + formRecord.versionUpgrade = true; + + FormItemInfo formItemInfo1; + formItemInfo1.SetFormId(7000L); + formItemInfo1.SetProviderBundleName(FORM_HOST_BUNDLE_NAME); + formItemInfo1.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + formItemInfo1.SetTemporaryFlag(true); + FormRecord formRecord1 = FormDataMgr::GetInstance().AllotFormRecord(formItemInfo1, callingUid); + + // add formHostRecord + FormItemInfo itemInfo; + FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); + + // test exec + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + + token_->Wait(); + + GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_007 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_provider_data_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_provider_data_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..32cbcbf7e40ef4dd2470c12986af0820663c453e --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormProviderDataTest") { + module_out_path = module_output_path + + sources = [ "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp" ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + + #"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + ] + + configs = [ "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormProviderDataTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31c9bd4191f960d53bce3e53c04eb5fc4656ad9b --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#define private public +#include "form_provider_data.h" +#undef private +#include "nlohmann/json.hpp" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; +const int32_t four = 4; +const int32_t ten = 10; +const int32_t eleven = 11; + +class FmsFormProviderDataTest : public testing::Test { +public: + void SetUp(); + void Test(); + bool InitJsonData(); + bool InitJsonData2(); + bool CreateJsonFileByJsonData1(const nlohmann::json &jsonData); + bool CreateJsonFileByJsonData2(const nlohmann::json &jsonData); + bool CreateMergeJsonFileByJsonData3(const nlohmann::json &jsonData); + // bool createJsonFileByStringData(); + + nlohmann::json jsonData_; +}; +void FmsFormProviderDataTest::SetUp() +{ + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + if (dirptr == nullptr) { + APP_LOGW("%{public}s, opendir is fail", __func__); + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { + APP_LOGE("%{public}s, dir create fail", __func__); + return; + } + } else { + closedir(dirptr); + } +} + +bool FmsFormProviderDataTest::InitJsonData() +{ + nlohmann::json tmpJson; + tmpJson["name"] = "li"; + tmpJson["age"] = ten; + jsonData_["0"] = tmpJson; + return true; +} + +bool FmsFormProviderDataTest::InitJsonData2() +{ + nlohmann::json tmpJson; + tmpJson["name"] = "wang"; + tmpJson["age"] = eleven; + jsonData_["1"] = tmpJson; + return true; +} + +bool FmsFormProviderDataTest::CreateJsonFileByJsonData1(const nlohmann::json &jsonData) +{ + std::ofstream o("/data/formmgr/ByJsonFile1.json"); + o.close(); + + std::fstream f("/data/formmgr/ByJsonFile1.json"); + if(f.good() == false) { + return false; + } + + f << std::setw(four) << jsonData << std::endl; + + f.close(); + return true; +} + +bool FmsFormProviderDataTest::CreateJsonFileByJsonData2(const nlohmann::json &jsonData) +{ + std::ofstream o("/data/formmgr/ByJsonFile2.json"); + o.close(); + + std::fstream f("/data/formmgr/ByJsonFile2.json"); + if(f.good() == false) { + return false; + } + + f << std::setw(four) << jsonData << std::endl; + + f.close(); + return true; +} + +bool FmsFormProviderDataTest::CreateMergeJsonFileByJsonData3(const nlohmann::json &jsonData) +{ + std::ofstream o("/data/formmgr/ByJsonFile3.json"); + o.close(); + + std::fstream f("/data/formmgr/ByJsonFile3.json"); + if(f.good() == false) { + return false; + } + + f << std::setw(four) << jsonData << std::endl; + + f.close(); + return true; +} + +HWTEST_F(FmsFormProviderDataTest, FmsFormProviderDataTest_001, TestSize.Level0) // create +{ + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_001 start"; + EXPECT_EQ(true, InitJsonData()); + FormProviderData formProviderData(jsonData_); + EXPECT_EQ(true, CreateJsonFileByJsonData1(formProviderData.jsonFormProviderData_)); + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_001 end"; +} + +HWTEST_F(FmsFormProviderDataTest, FmsFormProviderDataTest_002, TestSize.Level0) // test constructor with string +{ + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_002 start"; + EXPECT_EQ(true, InitJsonData()); + FormProviderData formProviderData(jsonData_.dump()); + EXPECT_EQ(true, CreateJsonFileByJsonData2(formProviderData.jsonFormProviderData_)); + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_002 end"; +} + +HWTEST_F(FmsFormProviderDataTest, FmsFormProviderDataTest_003, TestSize.Level0) // test GetDataString +{ + GTEST_LOG_(INFO) << "FmsFormProviderDataTest_003 start"; + EXPECT_EQ(true, InitJsonData()); + FormProviderData formProviderData(jsonData_); + GTEST_LOG_(INFO) << "print:" < +#include "form_ams_helper.h" +#include "form_bms_helper.h" +#define private public +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_refresh_limiter.h" +#include "form_host_interface.h" +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "form_provider_mgr.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormProviderMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormProviderMgrTest::SetUpTestCase() +{} + +void FmsFormProviderMgrTest::TearDownTestCase() +{} + +void FmsFormProviderMgrTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormProviderMgrTest::TearDown() +{} + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: AcquireForm Function + * FunctionPoints: FormMgr AcquireForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AcquireForm works with invalid formid. + */ + +HWTEST_F(FmsFormProviderMgrTest, AcquireForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 start"; + int64_t formId = 0x114514aa00000000; + FormProviderInfo formProviderInfo; + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormProviderMgr::GetInstance().AcquireForm(-114514L, formProviderInfo)); + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 end"; +} + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: AcquireForm Function + * FunctionPoints: FormMgr AcquireForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AcquireForm works without formrecord. + */ + +HWTEST_F(FmsFormProviderMgrTest, AcquireForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 start"; + int64_t formId = 0x11451aaa00000000; + FormProviderInfo formProviderInfo; + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST,FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 end"; +} + + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: AcquireForm Function + * FunctionPoints: FormMgr AcquireForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if AcquireForm works without form host record. + */ + +HWTEST_F(FmsFormProviderMgrTest, AcquireForm_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 start"; + int64_t formId = 0x1145aaaa00000000; + FormProviderInfo formProviderInfo; + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + EXPECT_EQ(ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, + FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 end"; +} + + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: RefreshForm Function + * FunctionPoints: FormMgr RefreshForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if RefreshForm works without form host record. + */ + +HWTEST_F(FmsFormProviderMgrTest, RefreshForm_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_004 start"; + int64_t formId = 0x1145aaaa00001200; + Want want; + int callingUid {0}; + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + FormItemInfo record; + record.SetFormId(formId); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_004 end"; +} + +/* + * Feature: FmsFormProviderMgr + * Function: FormMgr + * SubFunction: RefreshForm Function + * FunctionPoints: FormMgr RefreshForm interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if RefreshForm works without form host record. + */ + +HWTEST_F(FmsFormProviderMgrTest, RefreshForm_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 start"; + int64_t formId = 0x114514aa00000000; + Want want; + want.SetParam(Constants::KEY_IS_TIMER, true); + int callingUid {0}; + FormItemInfo record; + record.SetFormId(formId); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + EXPECT_EQ(ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 end"; +} +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..16adef3efec1680e7ddf8501ba56d4a741feaefa --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn @@ -0,0 +1,87 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormSetNextRefreshTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp", + ] + + include_dirs = [ + "//third_party/json/include", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/include", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + + #"${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + #"//foundation/appexecfwk/standard/services/formmgr:formmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + + #"${libs_path}/libeventhandler:libeventhandler_target", + #"//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("unittest") { + testonly = true + + deps = [ ":FmsFormSetNextRefreshTest" ] +} +############################################################################### diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76a978a7892529a009499e1663b0c128ac5a00db --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#define private public +#include "form_bms_helper.h" +#include "form_constants.h" +#include "form_timer_mgr.h" +#include "form_mgr_service.h" +#include "form_mgr_adapter.h" +#include "form_data_mgr.h" +#undef private +#include "mock_bundle_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const std::string FORM_HOST_BUNDLE_NAME = "com.form.provider.service"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormSetNextRefreshTest : public testing::Test { +public: + FmsFormSetNextRefreshTest() : formSetNextRefresh_(nullptr) + {} + ~FmsFormSetNextRefreshTest() + {} + std::shared_ptr formSetNextRefresh_ = DelayedSingleton::GetInstance(); + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +protected: + sptr mockBundleMgr_; +}; +void FmsFormSetNextRefreshTest::SetUpTestCase(void) +{} + +void FmsFormSetNextRefreshTest::TearDownTestCase(void) +{} + +void FmsFormSetNextRefreshTest::SetUp(void) +{ + formSetNextRefresh_ = std::make_shared(); + + formSetNextRefresh_->OnStart(); + + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); +} + +void FmsFormSetNextRefreshTest::TearDown(void) +{} + + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_001 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(formId is invalid) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_001 start"; + int64_t formId = 0; // invalid formId + int64_t nextTime = Constants::MIN_NEXT_TIME; + + EXPECT_EQ(ERR_FORM_INVALID_PARAM, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_001 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_002 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(not found in form record) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_002 start"; + int64_t formId = 2; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_002 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_003 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(BundleName is found in form record, but no dynamicRefreshTask) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_003 start"; + int64_t formId = 3; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // check dynamicRefreshTasks_ + EXPECT_EQ(true, FormTimerMgr::GetInstance().dynamicRefreshTasks_.empty()); + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + EXPECT_EQ(ERR_OK, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + + // check dynamicRefreshTasks_ + EXPECT_EQ(false, FormTimerMgr::GetInstance().dynamicRefreshTasks_.empty()); + + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_003 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_004 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(BundleName is not found in form record) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_004 start"; + int64_t formId = 4; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = "other_bundleName"; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_004 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_005 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(have dynamicRefreshTask , have IntervalTimerTasks) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_005 start"; + int64_t formId = 5; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // Creat dynamicRefreshTasks_ + DynamicRefreshItem theItem; + theItem.formId = formId; + theItem.settedTime = 1; + FormTimerMgr::GetInstance().dynamicRefreshTasks_.clear(); + FormTimerMgr::GetInstance().dynamicRefreshTasks_.emplace_back(theItem); + // check dynamicRefreshTasks_ + EXPECT_EQ(1, FormTimerMgr::GetInstance().dynamicRefreshTasks_.at(0).settedTime); + + // Create IntervalTimerTasks_ + FormTimer task; + task.formId = formId; + task.isEnable = true; + FormTimerMgr::GetInstance().AddIntervalTimer(task); + + EXPECT_EQ(ERR_OK, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + // check dynamicRefreshTasks_ + EXPECT_EQ(true, FormTimerMgr::GetInstance().dynamicRefreshTasks_.at(0).settedTime != 1); + + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_005 end"; +} + +/** + * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_006 + * @tc.name: SetNextRefreshTime + * @tc.desc: Verify that the return value is true.(timerRefreshedCount >= 50) + */ +HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_006 start"; + + int64_t formId = 6; + int64_t nextTime = Constants::MIN_NEXT_TIME; + + // creat formRecords_ + FormItemInfo iteminfo; + iteminfo.formId_ = formId; + iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; + iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + // set timerRefreshedCount + FormTimerMgr::GetInstance().refreshLimiter_.AddItem(formId); + auto iter = FormTimerMgr::GetInstance().refreshLimiter_.limiterMap_.find(formId); + if (iter == FormTimerMgr::GetInstance().refreshLimiter_.limiterMap_.end()) { + GTEST_LOG_(INFO) << "not found in limiterMap_!!!"; + } else { + iter->second.refreshCount = Constants::LIMIT_COUNT; + } + EXPECT_EQ(ERR_MAX_REFRESH, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + + GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_006 end"; +} +} diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e2ef82595509819b4c79a915dea1a99bd56fcef8 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn @@ -0,0 +1,88 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormSysEventReceiverTest") { + module_out_path = module_output_path + + sources = [ + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_sys_event_receiver_test.cpp" ] + + include_dirs = [ + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", + + # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/formmgr:fms_target", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//base/startup/appspawn_standard:appspawn_socket_client", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + + #"${services_path}/bundlemgr:bms_target", + "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormSysEventReceiverTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66aaa586a5ca0c8d619ef6245469997f7bfa59f8 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp @@ -0,0 +1,473 @@ +/* + * Copyright (c) 2021 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 "common_event_manager.h" +#include "common_event_data.h" +#include "common_event_support.h" +#include "form_ams_helper.h" +#include "form_constants.h" +#define private public +#include "form_data_mgr.h" +#include "form_db_cache.h" +#include "form_host_interface.h" +#include "form_mgr.h" +#undef private +#include "form_mgr_service.h" +#include "form_refresh_limiter.h" +#include "form_sys_event_receiver.h" +#include "if_system_ability_manager.h" +#include "inner_bundle_info.h" +#include "ipc_skeleton.h" +#include "form_bms_helper.h" +#include "iservice_registry.h" + +#include "mock_ability_manager.h" +#include "mock_bundle_manager.h" +#include "mock_form_host_client.h" +#include "permission/permission_kit.h" +#include "permission/permission.h" +#include "running_process_info.h" +#include "system_ability_definition.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::Security; + +namespace { +const std::string PERMISSION_NAME_REQUIRE_FORM = "ohos.permission.REQUIRE_FORM"; +const std::string PARAM_PROVIDER_PACKAGE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_BUNDLE_NAME = "com.form.provider.service"; +const std::string PARAM_PROVIDER_MODULE_NAME = "com.form.provider.app.test.abiliy"; +const std::string FORM_PROVIDER_ABILITY_NAME = "com.form.provider.app.test.abiliy"; +const std::string PARAM_FORM_NAME = "com.form.name.test"; + +const std::string FORM_JS_COMPOMENT_NAME = "jsComponentName"; +const std::string FORM_PROVIDER_MODULE_SOURCE_DIR = ""; + +const std::string FORM_HOST_BUNDLE_NAME = "com.form.host.app"; + +const int32_t PARAM_FORM_DIMENSION_VALUE = 1; + +const std::string KEY_UID = "uid"; +const std::string KEY_BUNDLE_NAME = "bundleName"; +const std::string DEVICE_ID = "ohos-phone1"; +const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; + +class FmsFormSysEventReceiverTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + void CreateEventData(std::string bundle, int64_t formId, int callingUid, std::string actionType, EventFwk::CommonEventData &eventData); + void CreateFormRecordAndFormInfo(std::string bundle, int64_t formId, int callingUid); + void ClearFormRecord(int64_t formId); + +protected: + sptr token_; + std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; +}; + +void FmsFormSysEventReceiverTest::SetUpTestCase() +{} + +void FmsFormSysEventReceiverTest::TearDownTestCase() +{} + +void FmsFormSysEventReceiverTest::SetUp() +{ + // APP_LOGI("fms_form_mgr_client_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); + token_ = new (std::nothrow) MockFormHostClient(); + + // Permission install + std::vector permList; + Permission::PermissionDef permDef; + permDef.permissionName = PERMISSION_NAME_REQUIRE_FORM; + permDef.bundleName = FORM_PROVIDER_BUNDLE_NAME; + permDef.grantMode = Permission::GrantMode::USER_GRANT; + permDef.availableScope = Permission::AvailableScope::AVAILABLE_SCOPE_ALL; + permDef.label = DEF_LABEL1; + permDef.labelId = 1; + permDef.description = DEF_LABEL1; + permDef.descriptionId = 1; + permList.emplace_back(permDef); + Permission::PermissionKit::AddDefPermissions(permList); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); + Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); +} + +void FmsFormSysEventReceiverTest::TearDown() +{} + +void FmsFormSysEventReceiverTest::CreateEventData(std::string bundle, int64_t formId, int callingUid, std::string actionType, EventFwk::CommonEventData &eventData) +{ + Want want; + want.SetAction(actionType); + want.SetParam(KEY_BUNDLE_NAME, bundle); + want.SetParam(KEY_UID, callingUid); + eventData.SetWant(want); +} + +void FmsFormSysEventReceiverTest::CreateFormRecordAndFormInfo(std::string bundle, int64_t formId, int callingUid) +{ + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetFormName(PARAM_FORM_NAME); + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(true); + + FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + + FormRecord realFormRecord; + FormDataMgr::GetInstance().GetFormRecord(formId, realFormRecord); + + FormDBInfo formDBInfo(formId, realFormRecord); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + + FormDataMgr::GetInstance().AllotFormHostRecord(record, token_, formId, callingUid); +} + +void FmsFormSysEventReceiverTest::ClearFormRecord(int64_t formId) +{ + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleProviderRemoved works. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_001 start"; + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcff00000000; + int callingUid {0}; + + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetFormName(PARAM_FORM_NAME); + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(false); + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_REMOVED); + want.SetParam(KEY_BUNDLE_NAME, bundle); + FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + // Set database info + FormDBInfo formDBInfo(formId, realFormRecord); + std::vector allFormInfo; + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // Set form host record + FormItemInfo info; + FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); + EventFwk::CommonEventData eventData; + eventData.SetWant(want); + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + FormDbCache::GetInstance().GetAllFormInfo(allFormInfo); + EXPECT_EQ(ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, FormDbCache::GetInstance().DeleteFormInfo(formId)); + FormDataMgr::GetInstance().DeleteFormRecord(formId); + FormDbCache::GetInstance().DeleteFormInfo(formId); + FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_001 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * [COMMON_EVENT_PACKAGE_DATA_CLEARED] want's uid is 0. formrecord's uid is 15. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_002 start"; + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcff00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED; + EventFwk::CommonEventData eventData; + int callingUidForWant = 0; + CreateEventData(bundle, formId, callingUidForWant, actionType, eventData); + CreateFormRecordAndFormInfo(bundle, formId, callingUid); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_002 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * [COMMON_EVENT_PACKAGE_DATA_CLEARED] want's uid and formrecord's and hostrecord's uid is 15. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_003 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + CreateFormRecordAndFormInfo(bundle, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_FALSE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_003 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_004 start"; + EventFwk::CommonEventData eventData; + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int callingUid {15}; + Want want; + FormRecord tempFormRecord; + eventData.SetWant(want); + want.SetParam(KEY_BUNDLE_NAME, bundle); + want.SetParam(KEY_UID, callingUid); + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_004 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * invalid action. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_005 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED + "ERROR"; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_005 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleBundleDataCleared works. + * [COMMON_EVENT_PACKAGE_DATA_CLEARED] There is 2 callingUids. + */ +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_006 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + + //CreateFormRecordAndFormInfo + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_FORM_NAME); + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); + record.SetFormName(PARAM_FORM_NAME); + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(true); + FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + ////AddFormUserUid + int new_callingUid = 150; + FormDataMgr::GetInstance().AddFormUserUid(formId, new_callingUid); + FormRecord realFormRecord; + FormDataMgr::GetInstance().GetFormRecord(formId, realFormRecord); + FormDBInfo formDBInfo(formId, realFormRecord); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + FormDataMgr::GetInstance().AllotFormHostRecord(record, token_, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_006 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleProviderUpdated works. + * [COMMON_EVENT_ABILITY_UPDATED] ProviderFormUpdated return false. delete formrecord. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_007 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + CreateFormRecordAndFormInfo(bundle, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_FALSE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_007 end"; +} + +/* + * Feature: FormMgrService + * Function: FormMgr + * SubFunction: OnReceiveEvent Functionss + * FunctionPoints: FormMgr OnReceiveEvent interface + * EnvConditions: Mobile that can run ohos test framework + * CaseDescription: Verify if HandleProviderUpdated works. + * [COMMON_EVENT_ABILITY_UPDATED] ProviderFormUpdated return true. refresh form. + */ + +HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_008 start"; + + std::string bundle = FORM_PROVIDER_BUNDLE_NAME; + int64_t formId = 0x0ffabcdf00000000; + int callingUid {15}; + std::string actionType = EventFwk::CommonEventSupport::COMMON_EVENT_ABILITY_UPDATED; + EventFwk::CommonEventData eventData; + CreateEventData(bundle, formId, callingUid, actionType, eventData); + + //CreateFormRecordAndFormInfo + FormItemInfo record; + record.SetFormId(formId); + record.SetProviderBundleName(bundle); + record.SetModuleName(PARAM_PROVIDER_MODULE_NAME); // model name + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); //ability name + record.SetFormName(PARAM_FORM_NAME); //form name + record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); + record.SetTemporaryFlag(true); + + FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); + FormRecord realFormRecord; + FormDataMgr::GetInstance().GetFormRecord(formId, realFormRecord); + FormDBInfo formDBInfo(formId, realFormRecord); + FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + FormDataMgr::GetInstance().AllotFormHostRecord(record, token_, formId, callingUid); + + FormRecord tempFormRecord; + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + FormSysEventReceiver testCase; + testCase.OnReceiveEvent(eventData); + + ASSERT_TRUE(FormDataMgr::GetInstance().GetFormRecord(formId, tempFormRecord)); + + ClearFormRecord(formId); + + GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_008 end"; +} + +} \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6cf9c8dbff8483f7caff7d10f8e795e5d8644242 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn @@ -0,0 +1,64 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/formmgrservice" + +ohos_unittest("FmsFormTimerMgrTest") { + module_out_path = module_output_path + + sources = [ "fms_form_timer_mgr_test.cpp" ] + + include_dirs = [ + "//foundation/appexecfwk/standard/common/log/include/", + "//foundation/appexecfwk/standard/services/formmgr/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", + ] + + configs = [ + "${services_path}/formmgr/test:formmgr_test_config", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${services_path}/formmgr:fms_target", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":FmsFormTimerMgrTest" ] +} diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efb9fe31a78ceb24f815c8e1a2da83c9ad84e3de --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp @@ -0,0 +1,600 @@ +/* + * Copyright (c) 2021 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 "common_event.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "form_constants.h" +#include "form_refresh_limiter.h" +#include "form_timer_mgr.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +const int64_t PARAM_FORM_ID_VALUE_1 = 20210712; +const int64_t PARAM_FORM_ID_VALUE_2 = 20210713; +const int64_t PARAM_FORM_ID_VALUE_3 = 20210714; +const int64_t PARAM_FORM_ID_VALUE_4 = 20210715; +const int64_t PARAM_FORM_ID_VALUE_5 = 20210716; +const int64_t PARAM_FORM_ID_VALUE_6 = 20210717; + +class FmsFormTimerMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: +}; + +void FmsFormTimerMgrTest::SetUpTestCase() {} +void FmsFormTimerMgrTest::TearDownTestCase() {} +void FmsFormTimerMgrTest::SetUp() {} +void FmsFormTimerMgrTest::TearDown() {} + +/** + * @tc.number: Fms_FormTimerMgr_0001 + * @tc.name: AddFormTimer. + * @tc.desc: Add duration form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0001 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 1 * Constants::MIN_PERIOD); + EXPECT_EQ(isOk, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0001 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0002 + * @tc.name: AddFormTimer. + * @tc.desc: Add scheduled form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0002 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 2, 50); + EXPECT_EQ(isOk, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0002 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0003 + * @tc.name: RemoveFormTimer. + * @tc.desc: Delete form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0003 start"; + bool isAddOk1 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 336 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk1, true); + bool isAddOk2 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 3, 30); + EXPECT_EQ(isAddOk2, true); + bool isDelOk1 = FormTimerMgr::GetInstance().RemoveFormTimer(PARAM_FORM_ID_VALUE_3); + EXPECT_EQ(isDelOk1, true); + bool isDelOk2 = FormTimerMgr::GetInstance().RemoveFormTimer(PARAM_FORM_ID_VALUE_4); + EXPECT_EQ(isDelOk2, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0003 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0004 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0004, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0004 start"; + bool isAddOk1 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 3 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk1, true); + + // TYPE_INTERVAL_CHANGE + FormTimerCfg timerCfg1; + timerCfg1.enableUpdate = true; + timerCfg1.updateDuration = 2 * Constants::MIN_PERIOD; + bool isUpdateOk1 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_1, + UpdateType::TYPE_INTERVAL_CHANGE, timerCfg1); + EXPECT_EQ(isUpdateOk1, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0004 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0005 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0005, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0005 start"; + bool isAddOk2 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 3, 30); + EXPECT_EQ(isAddOk2, true); + + // TYPE_ATTIME_CHANGE + FormTimerCfg timerCfg2; + timerCfg2.enableUpdate = true; + timerCfg2.updateAtHour = 6; + timerCfg2.updateAtMin = 55; + bool isUpdateOk2 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_2, + UpdateType::TYPE_ATTIME_CHANGE, timerCfg2); + EXPECT_EQ(isUpdateOk2, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0005 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0006 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_TO_ATTIME). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0006, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0006 start"; + bool isAddOk3 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 6 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk3, true); + + // TYPE_INTERVAL_TO_ATTIME + FormTimerCfg timerCfg3; + timerCfg3.enableUpdate = true; + timerCfg3.updateAtHour = 8; + timerCfg3.updateAtMin = 25; + bool isUpdateOk3 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_3, + UpdateType::TYPE_INTERVAL_TO_ATTIME, timerCfg3); + EXPECT_EQ(isUpdateOk3, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0006 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0007 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_TO_INTERVAL). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0007, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0007 start"; + bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 10, 30); + EXPECT_EQ(isAddOk4, true); + + // TYPE_ATTIME_TO_INTERVAL + FormTimerCfg timerCfg4; + timerCfg4.enableUpdate = true; + timerCfg4.updateDuration = 5 * Constants::MIN_PERIOD; + bool isUpdateOk4 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_4, + UpdateType::TYPE_ATTIME_TO_INTERVAL, timerCfg4); + EXPECT_EQ(isUpdateOk4, true); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0007 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0008 + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(COMMON_EVENT_TIME_CHANGED). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0008, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 11, 30); + EXPECT_EQ(isAddOk5, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0009 + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(COMMON_EVENT_TIMEZONE_CHANGED). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0009, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 11, 30); + EXPECT_EQ(isAddOk5, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0010 + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_RESET_LIMIT). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0010, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 11, 30); + EXPECT_EQ(isAddOk5, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(Constants::ACTION_UPDATEATTIMER); + want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_RESET_LIMIT); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0011 + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_STATIC_UPDATE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0011, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0011 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 11, 30); + EXPECT_EQ(isAddOk5, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(Constants::ACTION_UPDATEATTIMER); + want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_STATIC_UPDATE); + want.SetParam(Constants::KEY_WAKEUP_TIME, 90L); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0011 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0012 + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_DYNAMIC_UPDATE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0012, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0012 start"; + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_5, 11, 30); + EXPECT_EQ(isAddOk5, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(Constants::ACTION_UPDATEATTIMER); + want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_DYNAMIC_UPDATE); + want.SetParam(Constants::KEY_WAKEUP_TIME, 90L); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0012 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0013 + * @tc.name: AddFormTimer. + * @tc.desc: Add duration form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0013, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0013 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 0); + EXPECT_EQ(isOk, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0013 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0014 + * @tc.name: AddFormTimer. + * @tc.desc: Add scheduled form timer. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0014, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0014 start"; + bool isOk = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 0, 60); + EXPECT_EQ(isOk, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0014 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0015 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0015, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0015 start"; + bool isAddOk1 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 3 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk1, true); + + // TYPE_INTERVAL_CHANGE + FormTimerCfg timerCfg1; + timerCfg1.enableUpdate = true; + timerCfg1.updateDuration = 0; + bool isUpdateOk1 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_1, + UpdateType::TYPE_INTERVAL_CHANGE, timerCfg1); + EXPECT_EQ(isUpdateOk1, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0015 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0016 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_CHANGE). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0016, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0016 start"; + bool isAddOk2 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 3, 30); + EXPECT_EQ(isAddOk2, true); + + // TYPE_ATTIME_CHANGE + FormTimerCfg timerCfg2; + timerCfg2.enableUpdate = true; + timerCfg2.updateAtHour = 0; + timerCfg2.updateAtMin = 60; + bool isUpdateOk2 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_2, + UpdateType::TYPE_ATTIME_CHANGE, timerCfg2); + EXPECT_EQ(isUpdateOk2, false); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0016 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0017 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_INTERVAL_TO_ATTIME). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0017, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0017 start"; + bool isAddOk3 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 6 * Constants::MIN_PERIOD); + EXPECT_EQ(isAddOk3, true); + + // TYPE_INTERVAL_TO_ATTIME + FormTimerCfg timerCfg3; + timerCfg3.enableUpdate = true; + timerCfg3.updateAtHour = 0; + timerCfg3.updateAtMin = 60; + bool isUpdateOk3 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_3, + UpdateType::TYPE_INTERVAL_TO_ATTIME, timerCfg3); + EXPECT_EQ(isUpdateOk3, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0017 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0018 + * @tc.name: UpdateFormTimer. + * @tc.desc: Update form timer(TYPE_ATTIME_TO_INTERVAL). + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0018, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0018 start"; + bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 10, 30); + EXPECT_EQ(isAddOk4, true); + + // TYPE_ATTIME_TO_INTERVAL + FormTimerCfg timerCfg4; + timerCfg4.enableUpdate = true; + timerCfg4.updateDuration = 0; + bool isUpdateOk4 = FormTimerMgr::GetInstance().UpdateFormTimer(PARAM_FORM_ID_VALUE_4, + UpdateType::TYPE_ATTIME_TO_INTERVAL, timerCfg4); + EXPECT_EQ(isUpdateOk4, false); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0018 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0019 + * @tc.name: FormRefreshLimiter::AddItem. + * @tc.desc: AddItem success. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0019, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0019 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_1); + EXPECT_EQ(isAddOk, true); + + EXPECT_EQ(refreshLimiter.GetItemCount(), 1); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0019 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0020 + * @tc.name: FormRefreshLimiter::DeleteItem. + * @tc.desc: DeleteItem success. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0020, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0020 start"; + + FormRefreshLimiter refreshLimiter; + refreshLimiter.DeleteItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(refreshLimiter.GetItemCount(), 0); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0020 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0021 + * @tc.name: FormRefreshLimiter::IsEnableRefresh. + * @tc.desc: IsEnableRefresh. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0021, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0021 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + bool isEnableRefresh = refreshLimiter.IsEnableRefresh(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isEnableRefresh, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0021 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0022 + * @tc.name: FormRefreshLimiter::Increase. + * @tc.desc: Increase refreshCount. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0022, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0022 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + + int count = refreshLimiter.GetRefreshCount(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(count, 1); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0022 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0023 + * @tc.name: FormRefreshLimiter::ResetLimit. + * @tc.desc: ResetLimit. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0023, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0023 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + + refreshLimiter.ResetLimit(); + + int count = refreshLimiter.GetRefreshCount(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(count, 0); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0023 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0024 + * @tc.name: FormRefreshLimiter::Increase. + * @tc.desc: report refresh to 50 count. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0024, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0024 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT; iIndex++){ + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + } + + int count = refreshLimiter.GetRefreshCount(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(count, Constants::LIMIT_COUNT); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0024 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0025 + * @tc.name: FormRefreshLimiter::IsEnableRefresh. + * @tc.desc: report refresh to 50 count. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0025, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0025 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + } + + bool isEnableRefresh = refreshLimiter.IsEnableRefresh(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isEnableRefresh, false); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0025 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0026 + * @tc.name: FormRefreshLimiter::MarkRemind. + * @tc.desc: Mark remind when refresh count >= 50. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0026, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0026 start"; + + FormRefreshLimiter refreshLimiter; + bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); + EXPECT_EQ(isAddOk, true); + for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); + } + + refreshLimiter.MarkRemind(PARAM_FORM_ID_VALUE_6); + + std::vector vIdlist = refreshLimiter.GetRemindList(); + EXPECT_EQ(vIdlist.size() > 0, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0026 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0027 + * @tc.name: OnIntervalTimeOut. + * @tc.desc: Interval timer timeout. + */ +HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0027, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 start"; + bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_6, 10, 30); + EXPECT_EQ(isAddOk4, true); + + std::this_thread::sleep_for(std::chrono::milliseconds(Constants::MIN_PERIOD)); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 end"; +} +} diff --git a/services/test/mock/include/mock_ability_mgr_host.h b/services/test/mock/include/mock_ability_mgr_host.h index 31d9f786934bfb6b43f3e7f4d4ed9f32e55c72b3..1a0080a53e74ffbf464a1ecfc6ca65e2a515686d 100644 --- a/services/test/mock/include/mock_ability_mgr_host.h +++ b/services/test/mock/include/mock_ability_mgr_host.h @@ -184,6 +184,11 @@ public: return 0; } + int UpdateConfiguration(const DummyConfiguration &config) override + { + return 0; + } + virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override { @@ -235,6 +240,43 @@ public: { return 0; } + int MoveMissionToFloatingStack(const MissionOption &missionOption) override + { + return 0; + } + int MoveMissionToSplitScreenStack(const MissionOption &missionOption) override + { + return 0; + } + int MinimizeMultiWindow(int missionId) override + { + return 0; + } + int MaximizeMultiWindow(int missionId) override + { + return 0; + } + int GetFloatingMissions(std::vector &list) override + { + return 0; + } + int CloseMultiWindow(int missionId) override + { + return 0; + } + int SetMissionStackSetting(const StackSetting &stackSetting) override + { + return 0; + } + int StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, int requestCode) override + { + return 0; + } + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) override + { + return 0; + } }; } // namespace AppExecFwk diff --git a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp index 508b2f449e055921203eedde79a59206a4a797f5..20e10a2cb4575781565d8d08b6368436d0ff6b70 100755 --- a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp +++ b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp @@ -377,7 +377,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); auto appInfo = GetApplicationInfo("com.ohos.test.helloworld"); sptr mockAppScheduler = new (std::nothrow) MockAppScheduler(); - ASSERT_TRUE(mockAppScheduler); + EXPECT_TRUE(mockAppScheduler); TestProcessInfo testProcessInfo; testProcessInfo.pid = pid; @@ -473,7 +473,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_002, TestSize.Level3) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_003, TestSize.Level3) { pid_t pid = 1025; - ASSERT_TRUE(serviceInner_); + EXPECT_TRUE(serviceInner_); std::shared_ptr appRunningRecord = nullptr; std::vector> tokens; auto abilityInfo = std::make_shared(); @@ -643,7 +643,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) exit(0); } - ASSERT_TRUE(pid > 0); + EXPECT_TRUE(pid > 0); usleep(50000); sptr token = GetAbilityToken(); @@ -868,10 +868,10 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_010, TestSize.Level3) char index[32]; int ref = snprintf_s(index, sizeof(index), sizeof(index) - 1, "%d", i); - ASSERT_TRUE(ref > 0); + EXPECT_TRUE(ref > 0); char name[128]; ref = snprintf_s(name, sizeof(name), sizeof(name) - 1, "com.ohos.test.helloworld%d", i); - ASSERT_TRUE(ref > 0); + EXPECT_TRUE(ref > 0); auto abilityInfo = GetAbilityInfo(index, "MainAbility", index, name); auto appInfo = GetApplicationInfo(name); auto token = new (std::nothrow) MockAbilityToken(); @@ -882,7 +882,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_010, TestSize.Level3) appRunningRecord = StartProcessAndLoadAbility(mockAppScheduler[i], token, abilityInfo, appInfo, testProcessInfo); - ASSERT_TRUE(appRunningRecord); + EXPECT_TRUE(appRunningRecord); ChangeAbilityStateAfterAppStart(mockAppScheduler[i], testProcessInfo.pid); @@ -966,12 +966,12 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_012, TestSize.Level0) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_013, TestSize.Level3) { - ASSERT_TRUE(serviceInner_); - ASSERT_TRUE(serviceInner_->remoteClientManager_); - ASSERT_TRUE(serviceInner_->remoteClientManager_->GetSpawnClient()); + EXPECT_TRUE(serviceInner_); + EXPECT_TRUE(serviceInner_->remoteClientManager_); + EXPECT_TRUE(serviceInner_->remoteClientManager_->GetSpawnClient()); auto mockAppSpawnSocket = std::make_shared(); - ASSERT_TRUE(mockAppSpawnSocket); + EXPECT_TRUE(mockAppSpawnSocket); serviceInner_->remoteClientManager_->GetSpawnClient()->SetSocket(mockAppSpawnSocket); EXPECT_EQ(serviceInner_->QueryAppSpawnConnectionState(), SpawnConnectionState::STATE_NOT_CONNECT); diff --git a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp index 63cf32cbfc806f721a7c15a3a7f664bd82f9c984..12eadc519bf9b19e83c6f7288ef87a30a3eb091c 100644 --- a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp +++ b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp @@ -139,9 +139,9 @@ void AppMgrServiceModuleTest::TearDown() */ HWTEST_F(AppMgrServiceModuleTest, AttachApplication_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); - ASSERT_TRUE(testRemoteObject_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(testRemoteObject_); for (int i = 0; i < COUNT; ++i) { EXPECT_CALL(*mockAppMgrServiceInner_, AddAppDeathRecipient(_, _)) @@ -164,8 +164,8 @@ HWTEST_F(AppMgrServiceModuleTest, AttachApplication_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, ApplicationForegrounded_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); int32_t testRecordId = 123; bool testResult = false; @@ -198,8 +198,8 @@ HWTEST_F(AppMgrServiceModuleTest, ApplicationForegrounded_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, ApplicationBackgrounded_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); int32_t testRecordId = 123; bool testResult = false; @@ -232,8 +232,8 @@ HWTEST_F(AppMgrServiceModuleTest, ApplicationBackgrounded_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, ApplicationTerminated_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); int32_t testRecordId = 123; bool testResult = false; @@ -266,9 +266,9 @@ HWTEST_F(AppMgrServiceModuleTest, ApplicationTerminated_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, AbilityCleaned_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); - ASSERT_TRUE(testRemoteObject_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(testRemoteObject_); bool testResult = false; Semaphore sem(0); @@ -300,8 +300,8 @@ HWTEST_F(AppMgrServiceModuleTest, AbilityCleaned_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, ClearUpApplicationData_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); std::string testAppName("testApp"); bool testResult = false; @@ -334,8 +334,8 @@ HWTEST_F(AppMgrServiceModuleTest, ClearUpApplicationData_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, IsBackgroundRunningRestricted_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); std::string testAppName("testApp"); bool testResult = false; @@ -370,8 +370,8 @@ HWTEST_F(AppMgrServiceModuleTest, IsBackgroundRunningRestricted_001, TestSize.Le */ HWTEST_F(AppMgrServiceModuleTest, GetAllRunningProcesses_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); std::vector testRunningProcessInfo; @@ -410,8 +410,8 @@ HWTEST_F(AppMgrServiceModuleTest, GetAllRunningProcesses_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, KillApplication_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); std::string testBundleName("testApp"); bool testResult = false; @@ -446,8 +446,8 @@ HWTEST_F(AppMgrServiceModuleTest, KillApplication_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, QueryServiceState_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); - ASSERT_TRUE(mockAppMgrServiceInner_); + EXPECT_TRUE(appMgrService_); + EXPECT_TRUE(mockAppMgrServiceInner_); SpawnConnectionState testSpawnConnectionState = SpawnConnectionState::STATE_CONNECTED; Semaphore sem(0); @@ -477,7 +477,7 @@ HWTEST_F(AppMgrServiceModuleTest, QueryServiceState_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, GetAmsMgr_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); + EXPECT_TRUE(appMgrService_); auto amsMgr = appMgrService_->GetAmsMgr(); diff --git a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp index 163a90011003064e87d890dcc30ca3af62aac46b..f565d0ef49b9bb0e33115fc4c098be6f5d7ee4d2 100644 --- a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp +++ b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp @@ -63,7 +63,7 @@ protected: void CheckLaunchApplication(const sptr &mockApplication, const unsigned long index, std::shared_ptr record, const std::string &testPoint) const { - ASSERT_TRUE(record != nullptr) << "record is nullptr!"; + EXPECT_TRUE(record != nullptr) << "record is nullptr!"; sptr client = iface_cast(mockApplication); record->SetApplicationClient(client); @@ -92,10 +92,10 @@ protected: const std::shared_ptr abilityInfo, const std::shared_ptr record, const int index, RecordQueryResult &result) const { - ASSERT_TRUE(service_ != nullptr) << "init service fail!"; - ASSERT_TRUE(appInfo != nullptr) << "appInfo is nullptr!"; - ASSERT_TRUE(abilityInfo != nullptr) << "abilityInfo is nullptr!"; - ASSERT_TRUE(record != nullptr) << "record is nullptr!"; + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; + EXPECT_TRUE(appInfo != nullptr) << "appInfo is nullptr!"; + EXPECT_TRUE(abilityInfo != nullptr) << "abilityInfo is nullptr!"; + EXPECT_TRUE(record != nullptr) << "record is nullptr!"; auto abilityRecord = record->GetAbilityRunningRecord(GetTestAbilityName(index)); int32_t id = record->GetRecordId(); auto name = record->GetName(); @@ -111,7 +111,7 @@ protected: sptr tokenFromServ = abilityRecordFromServ->GetToken(); auto nameFromServ = appRecordFromServ->GetName(); auto abilityNameFromServ = abilityRecordFromServ->GetName(); - ASSERT_TRUE(result.appExists) << "result is wrong!"; + EXPECT_TRUE(result.appExists) << "result is wrong!"; EXPECT_TRUE(id == idFromServ) << "fail, RecordId is not equal!"; EXPECT_TRUE(tokenFromServ.GetRefPtr() == token.GetRefPtr()) << "fail, token is not equal!"; EXPECT_EQ(name, nameFromServ) << "fail, app record name is not equal!"; @@ -170,7 +170,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStart_001, TestSize.Level0) std::string processName = GetTestAppName(index); RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); - ASSERT_TRUE(record != nullptr) << ",create apprunningrecord fail!"; + EXPECT_TRUE(record != nullptr) << ",create apprunningrecord fail!"; ASSERT_FALSE(result.appExists) << ",result is wrong!"; // check apprunningrecord @@ -196,7 +196,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStart_001, TestSize.Level0) service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, newResult); EXPECT_TRUE(newRecord); auto stateFromRec = newRecord->GetState(); - ASSERT_TRUE(newResult.appExists) << "fail, app is not exist!"; + EXPECT_TRUE(newResult.appExists) << "fail, app is not exist!"; EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_FOREGROUND); // clear apprunningrecord @@ -230,7 +230,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, MultiApplicationStart_002, TestSize.Leve RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); - ASSERT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; ASSERT_FALSE(result.appExists) << "result is wrong!"; // check abilityrunningrecord & apprunningrecord @@ -262,7 +262,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, MultiApplicationStart_002, TestSize.Leve */ HWTEST_F(AmsAppRunningRecordModuleTest, ScheduleTrimMemory_003, TestSize.Level1) { - ASSERT_TRUE(service_ != nullptr) << "init service fail!"; + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; // init AppRunningRecord unsigned long index = 0; @@ -273,7 +273,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ScheduleTrimMemory_003, TestSize.Level1) appInfo->name = GetTestAppName(index); RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); - ASSERT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; ASSERT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication @@ -310,7 +310,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ScheduleTrimMemory_003, TestSize.Level1) */ HWTEST_F(AmsAppRunningRecordModuleTest, LowMemoryWarning_004, TestSize.Level1) { - ASSERT_TRUE(service_ != nullptr) << "init service fail!"; + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; // init AppRunningRecord unsigned long index = 0; @@ -321,7 +321,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, LowMemoryWarning_004, TestSize.Level1) appInfo->name = GetTestAppName(index); RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); - ASSERT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; ASSERT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication @@ -358,7 +358,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, LowMemoryWarning_004, TestSize.Level1) */ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStartAndQuit_005, TestSize.Level2) { - ASSERT_TRUE(service_ != nullptr) << "init service fail!"; + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; unsigned long index = 0; int startCount = 10000; @@ -372,7 +372,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStartAndQuit_005, TestSize.Le RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); - ASSERT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; // LaunchApplication sptr mockApplication(new MockApplication()); @@ -428,7 +428,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStartAndQuit_005, TestSize.Le */ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStatusChange_006, TestSize.Level2) { - ASSERT_TRUE(service_ != nullptr) << "init service fail!"; + EXPECT_TRUE(service_ != nullptr) << "init service fail!"; // init AppRunningRecord unsigned long index = 0; @@ -439,7 +439,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStatusChange_006, TestSize.Le appInfo->name = GetTestAppName(index); RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); - ASSERT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; // LaunchApplication sptr mockApplication(new MockApplication()); diff --git a/services/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp b/services/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp index eee1fba58269d022703f50907513e5755a6a4988..27ebd33e6f1db723cd07b91ba7f3aa68e46bf131 100644 --- a/services/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp +++ b/services/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp @@ -71,7 +71,7 @@ HWTEST_F(AmsServiceStartModuleTest, AmsStartupMoretimes_001, TestSize.Level1) { APP_LOGI("AmsStartupMoretimes_001 start"); std::shared_ptr appMgrService = std::make_shared(); - ASSERT_TRUE(appMgrService.get() != nullptr); + EXPECT_TRUE(appMgrService.get() != nullptr); std::shared_ptr innerService = std::make_shared(); appMgrService->SetInnerService(innerService); EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); @@ -98,7 +98,7 @@ HWTEST_F(AmsServiceStartModuleTest, AmsStartupMoretimes_002, TestSize.Level1) { APP_LOGI("AmsStartupMoretimes_002 start"); std::shared_ptr appMgrService = std::make_shared(); - ASSERT_TRUE(appMgrService.get() != nullptr); + EXPECT_TRUE(appMgrService.get() != nullptr); std::shared_ptr innerService = std::make_shared(); appMgrService->SetInnerService(innerService); EXPECT_EQ(ServiceRunningState::STATE_NOT_START, appMgrService->QueryServiceState().serviceRunningState); diff --git a/services/test/moduletest/common/bms/bundle_installer_test/BUILD.gn b/services/test/moduletest/common/bms/bundle_installer_test/BUILD.gn index 1dc596fe57e6f3b465c9522640070ab78efce635..e73c5409710e04b7365ef60b136c202d6723c930 100755 --- a/services/test/moduletest/common/bms/bundle_installer_test/BUILD.gn +++ b/services/test/moduletest/common/bms/bundle_installer_test/BUILD.gn @@ -32,6 +32,7 @@ ohos_moduletest("BmsBundleInstallerModuleTest") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include/bundlemgr", "//foundation/aafwk/standard/interfaces/innerkits/want/include", "//third_party/json/include", + "//third_party/jsoncpp/include", "${services_path}/test/mock/include", ] @@ -46,6 +47,9 @@ ohos_moduletest("BmsBundleInstallerModuleTest") { "${services_path}/bundlemgr/src/installd/installd_host_impl.cpp", "${services_path}/bundlemgr/src/installd/installd_operator.cpp", "${services_path}/bundlemgr/src/installd/installd_service.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += bundle_install_sources @@ -73,6 +77,7 @@ ohos_moduletest("BmsBundleInstallerModuleTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/test/moduletest/common/bms/bundle_installer_test/bms_bundle_installer_module_test.cpp b/services/test/moduletest/common/bms/bundle_installer_test/bms_bundle_installer_module_test.cpp index e2b949af39a4c1c334b51b814f4a157a2525241e..db27d0673b631deeddc63fdd598e2430fc52d503 100644 --- a/services/test/moduletest/common/bms/bundle_installer_test/bms_bundle_installer_module_test.cpp +++ b/services/test/moduletest/common/bms/bundle_installer_test/bms_bundle_installer_module_test.cpp @@ -154,7 +154,10 @@ protected: "defaultHeight": 100, "minWidth": 0, "defaultWidth": 200 - } + }, + "labelId": 1, + "descriptionId": 1, + "iconId": 1 }, "com.ohos.launchercom.ohos.launchercom.ohos.launcher.MainAbility": { "applicationName": "com.ohos.launcher", @@ -517,7 +520,7 @@ void BmsBundleInstallerModuleTest::SaveBundleDataToStorage(std::unique_ptrPut(key, value); if (status != Status::SUCCESS) { std::cout << static_cast(status) << std::endl; - ASSERT_TRUE(false) << "save fail"; + EXPECT_TRUE(false) << "save fail"; } } @@ -530,7 +533,7 @@ void BmsBundleInstallerModuleTest::DeleteBundleDataToStorage( Key key(keyString); status = kvStorePtr->Delete(key); if (status != Status::SUCCESS) { - ASSERT_TRUE(false) << "delete fail"; + EXPECT_TRUE(false) << "delete fail"; } } @@ -626,13 +629,13 @@ void BmsBundleInstallerModuleTest::SetUpTestCase() { if (access(ROOT_DIR.c_str(), F_OK) != 0) { bool result = OHOS::ForceCreateDirectory(ROOT_DIR); - ASSERT_TRUE(result); + EXPECT_TRUE(result); } if (chown(ROOT_DIR.c_str(), ROOT_UID, ROOT_UID) != 0) { - ASSERT_TRUE(false); + EXPECT_TRUE(false); } if (chmod(ROOT_DIR.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) { - ASSERT_TRUE(false); + EXPECT_TRUE(false); } } @@ -665,7 +668,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, SystemAppInstall_0100, Function | MediumT { std::string bundleName = SYSTEM_BUNDLE_NAME + "s1"; std::shared_ptr dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo bundleInfo; bool ret = false; int checkCount = 0; @@ -689,7 +692,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, SystemAppInstall_0200, Function | MediumT { int bundleNum = 2; std::shared_ptr dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo bundleInfo; for (int i = 1; i <= bundleNum; i++) { @@ -718,7 +721,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, SystemAppInstall_0300, Function | MediumT { std::string norBundleName = SYSTEM_BUNDLE_NAME + "s2"; std::shared_ptr dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo bundleInfo; bool ret = false; int checkCount = 0; @@ -752,7 +755,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, SystemAppInstall_0400, Function | MediumT std::string bundleName = SYSTEM_BUNDLE_NAME + "s3"; CheckFileNonExist(bundleName); std::shared_ptr dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo bundleInfo; bool ret = false; int checkCount = 0; @@ -776,7 +779,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, SystemAppInstall_0500, Function | MediumT std::string bundleName = SYSTEM_BUNDLE_NAME + "s4"; CheckFileNonExist(bundleName); std::shared_ptr dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo bundleInfo; bool ret = false; int checkCount = 0; @@ -798,19 +801,19 @@ HWTEST_F(BmsBundleInstallerModuleTest, SystemAppInstall_0500, Function | MediumT HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0100, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; CheckFileExist(bundleName); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -826,14 +829,14 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0100, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0200, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK); + EXPECT_EQ(receiver->GetResultCode(), ERR_OK); std::string bundleName = THIRD_BUNDLE_NAME + "1"; CheckFileExist(bundleName); @@ -841,7 +844,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0200, Function | MediumTe StartBundleMgrService(); CheckFileExist(bundleName); std::shared_ptr dataMgr = GetBundleDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); BundleInfo bundleInfo; bool ret = false; ret = dataMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -850,7 +853,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0200, Function | MediumTe installParam.userId = Constants::DEFAULT_USERID; OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK); } @@ -865,21 +868,21 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0200, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0300, Function | MediumTest | Level2) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle12" + ERROR_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME); + EXPECT_EQ(receiver->GetResultCode(), ERR_APPEXECFWK_INSTALL_INVALID_HAP_NAME); std::string bundleName = THIRD_BUNDLE_NAME + "12"; CheckFileNonExist(bundleName); BundleInfo info; std::shared_ptr bms = DelayedSingleton::GetInstance(); auto dataMgr = bms->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool isBundleExist = dataMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info); EXPECT_FALSE(isBundleExist); } @@ -893,11 +896,11 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0300, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0400, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleName = THIRD_BUNDLE_NAME + "5"; @@ -914,10 +917,10 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0400, Function | MediumTe StartInstalld(); std::this_thread::sleep_for(1ms); installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK); + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK); CheckFileExist(bundleName); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK); } @@ -932,27 +935,27 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0400, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0500, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr normalInstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(normalInstall, nullptr); + EXPECT_NE(normalInstall, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle9" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, normalInstall); - ASSERT_EQ(normalInstall->GetResultCode(), ERR_OK); + EXPECT_EQ(normalInstall->GetResultCode(), ERR_OK); std::string bundleName = THIRD_BUNDLE_NAME + "2"; CheckFileExist(bundleName); std::string upgradeFilePath = BUNDLE_TMPPATH + "bmsThirdBundle7" + Constants::INSTALL_FILE_SUFFIX; OHOS::sptr replaceInstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(replaceInstall, nullptr); + EXPECT_NE(replaceInstall, nullptr); installParam.installFlag = InstallFlag::REPLACE_EXISTING; installer->Install(upgradeFilePath, installParam, replaceInstall); - ASSERT_EQ(replaceInstall->GetResultCode(), ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE); + EXPECT_EQ(replaceInstall->GetResultCode(), ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE); CheckFileExist(bundleName); OHOS::sptr uninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(uninstall, nullptr); + EXPECT_NE(uninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, uninstall); EXPECT_EQ(uninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -968,23 +971,23 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0500, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0600, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr normalInstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(normalInstall, nullptr); + EXPECT_NE(normalInstall, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle7" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, normalInstall); - ASSERT_EQ(normalInstall->GetResultCode(), ERR_OK); + EXPECT_EQ(normalInstall->GetResultCode(), ERR_OK); std::string bundleName = THIRD_BUNDLE_NAME + "2"; CheckFileExist(bundleName); std::string upgradeFilePath = BUNDLE_TMPPATH + "bmsThirdBundle9" + Constants::INSTALL_FILE_SUFFIX; OHOS::sptr replaceInstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(replaceInstall, nullptr); + EXPECT_NE(replaceInstall, nullptr); installParam.installFlag = InstallFlag::REPLACE_EXISTING; installer->Install(upgradeFilePath, installParam, replaceInstall); - ASSERT_EQ(replaceInstall->GetResultCode(), ERR_OK); + EXPECT_EQ(replaceInstall->GetResultCode(), ERR_OK); CheckFileExist(bundleName); StopBundleMgrService(); @@ -994,14 +997,14 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0600, Function | MediumTe BundleInfo info; std::shared_ptr bms = DelayedSingleton::GetInstance(); auto dataMgr = bms->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool isBundleExist = dataMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info); EXPECT_TRUE(isBundleExist); std::cout << "info-name:" << info.name << std::endl; OHOS::sptr uninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(uninstall, nullptr); + EXPECT_NE(uninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, uninstall); EXPECT_EQ(uninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1017,27 +1020,27 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0600, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0700, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr normalInstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(normalInstall, nullptr); + EXPECT_NE(normalInstall, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle7" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, normalInstall); - ASSERT_EQ(normalInstall->GetResultCode(), ERR_OK); + EXPECT_EQ(normalInstall->GetResultCode(), ERR_OK); std::string bundleName = THIRD_BUNDLE_NAME + "2"; CheckFileExist(bundleName); std::string upgradeFilePath = BUNDLE_TMPPATH + "bmsThirdBundle10" + Constants::INSTALL_FILE_SUFFIX; OHOS::sptr replaceInstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(replaceInstall, nullptr); + EXPECT_NE(replaceInstall, nullptr); installParam.installFlag = InstallFlag::REPLACE_EXISTING; installer->Install(upgradeFilePath, installParam, replaceInstall); - ASSERT_EQ(replaceInstall->GetResultCode(), ERR_OK); + EXPECT_EQ(replaceInstall->GetResultCode(), ERR_OK); CheckFileExist(bundleName); OHOS::sptr uninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(uninstall, nullptr); + EXPECT_NE(uninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, uninstall); EXPECT_EQ(uninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1052,29 +1055,29 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0700, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0800, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; CheckFileExist(bundleName, modulePackage); bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle4" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; CheckFileExist(bundleName, modulePackage2); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1089,17 +1092,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0800, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0900, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle3" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {}; @@ -1107,13 +1110,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0900, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle6" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1128,17 +1131,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_0900, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1000, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle3" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {}; @@ -1146,13 +1149,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1000, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle4" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {"bmsThirdBundle_A1"}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1168,17 +1171,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1000, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1100, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle3" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {}; @@ -1186,13 +1189,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1100, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle5" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {"bmsThirdBundle_A1", "bmsThirdBundle_A2"}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1207,17 +1210,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1100, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1200, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {"bmsThirdBundle_A1"}; @@ -1225,13 +1228,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1200, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle6" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1246,17 +1249,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1200, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1300, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {"bmsThirdBundle_A1"}; @@ -1264,13 +1267,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1300, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle4" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {"bmsThirdBundle_A1"}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1285,17 +1288,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1300, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1400, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {"bmsThirdBundle_A1"}; @@ -1303,13 +1306,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1400, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle5" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {"bmsThirdBundle_A1", "bmsThirdBundle_A2"}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1325,17 +1328,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1400, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1500, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle2" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {"bmsThirdBundle_A1", "bmsThirdBundle_A2"}; @@ -1343,13 +1346,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1500, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle6" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1364,17 +1367,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1500, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1600, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle2" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {"bmsThirdBundle_A1", "bmsThirdBundle_A2"}; @@ -1382,13 +1385,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1600, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle4" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {"bmsThirdBundle_A1"}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1403,17 +1406,17 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1600, Function | MediumTe HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1700, Function | MediumTest | Level1) { auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); OHOS::sptr receiver2 = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver2, nullptr); + EXPECT_NE(receiver2, nullptr); InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; std::string bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle2" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BUNDLE_NAME + "1"; std::string modulePackage = "com.third.hiworld.example.h1"; std::vector hap1AbilityNames = {"bmsThirdBundle_A1", "bmsThirdBundle_A2"}; @@ -1421,13 +1424,13 @@ HWTEST_F(BmsBundleInstallerModuleTest, ThirdAppInstall_1700, Function | MediumTe bundleFilePath = BUNDLE_TMPPATH + "bmsThirdBundle5" + Constants::INSTALL_FILE_SUFFIX; installer->Install(bundleFilePath, installParam, receiver2); - ASSERT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; + EXPECT_EQ(receiver2->GetResultCode(), ERR_OK) << "install fail!" << bundleFilePath; std::string modulePackage2 = "com.third.hiworld.example.h2"; std::vector hap2AbilityNames = {"bmsThirdBundle_A1", "bmsThirdBundle_A2"}; CheckFileExist(bundleName, modulePackage2, hap2AbilityNames); OHOS::sptr recUninstall = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(recUninstall, nullptr); + EXPECT_NE(recUninstall, nullptr); installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, recUninstall); EXPECT_EQ(recUninstall->GetResultCode(), ERR_OK) << "uninstall fail!" << bundleName; @@ -1456,7 +1459,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage_0100, Function | Medium std::string bundleName = baseBundleName + std::to_string(i * saveTimes + j); InnerBundleInfo innerBundleInfo = CreateInnerBundleInfo(bundleName); bool res = bundleDataStorage.SaveStorageBundleInfo(deviceId_, innerBundleInfo); - ASSERT_TRUE(res) << "save bundle data fail"; + EXPECT_TRUE(res) << "save bundle data fail"; bundleNames.emplace_back(bundleName); innerBundleInfoStrs.emplace_back(innerBundleInfo.ToString()); innerBundleInfos.emplace_back(innerBundleInfo); @@ -1467,7 +1470,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage_0100, Function | Medium */ std::map> dataMap; bool loadRes = bundleDataStorage.LoadAllData(dataMap); - ASSERT_TRUE(loadRes) << "load data fail!!!"; + EXPECT_TRUE(loadRes) << "load data fail!!!"; for (std::string item : bundleNames) { std::map innerBundleInfoMap = dataMap[item]; for (auto iter = innerBundleInfoMap.begin(); iter != innerBundleInfoMap.end(); ++iter) { @@ -1485,7 +1488,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage_0100, Function | Medium } for (InnerBundleInfo inner : innerBundleInfos) { bool delRes = bundleDataStorage.DeleteStorageBundleInfo(deviceId_, inner); - ASSERT_TRUE(delRes) << "delete data fail!!!"; + EXPECT_TRUE(delRes) << "delete data fail!!!"; } } @@ -1508,7 +1511,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage_0200, Function | Medium std::string bundleName = baseBundleName + std::to_string(i); InnerBundleInfo innerBundleInfo = CreateInnerBundleInfo(bundleName); bool res = bundleDataStorage.SaveStorageBundleInfo(deviceId_, innerBundleInfo); - ASSERT_TRUE(res) << "save bundle data fail"; + EXPECT_TRUE(res) << "save bundle data fail"; bundleNames.emplace_back(bundleName); innerBundleInfos.emplace_back(innerBundleInfo); } @@ -1522,7 +1525,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage_0200, Function | Medium std::shared_ptr dataMgr = GetBundleDataMgr(); if (dataMgr == nullptr) { - ASSERT_TRUE(false); + EXPECT_TRUE(false); } for (std::string item : bundleNames) { @@ -1535,7 +1538,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage_0200, Function | Medium for (InnerBundleInfo inner : innerBundleInfos) { bool delRes = bundleDataStorage.DeleteStorageBundleInfo(deviceId_, inner); - ASSERT_TRUE(delRes) << "delete data fail!!!"; + EXPECT_TRUE(delRes) << "delete data fail!!!"; } } @@ -1553,7 +1556,7 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage003, TestSize.Level3) DistributedKvDataManager dataManager; std::unique_ptr kvStorePtr = GetKvStorePtr(dataManager); if (!kvStorePtr) { - ASSERT_TRUE(false) << "kvStorePtr is nullptr"; + EXPECT_TRUE(false) << "kvStorePtr is nullptr"; } int saveTimes = 100; @@ -1579,14 +1582,14 @@ HWTEST_F(BmsBundleInstallerModuleTest, BundleDataStorage003, TestSize.Level3) BundleDataStorageDatabase bundleDataStorage; std::map> bundleDatas; bool getBundleData = bundleDataStorage.LoadAllData(bundleDatas); - ASSERT_TRUE(getBundleData) << "get bundle data from database fail!"; + EXPECT_TRUE(getBundleData) << "get bundle data from database fail!"; StopBundleMgrService(); StartBundleMgrService(); std::shared_ptr dataMgr = GetBundleDataMgr(); if (dataMgr == nullptr) { - ASSERT_TRUE(false); + EXPECT_TRUE(false); } ApplicationInfo appInfo; for (int i = 0; i < saveTimes; i++) { diff --git a/services/test/moduletest/common/bms/bundle_uninstall_test/BUILD.gn b/services/test/moduletest/common/bms/bundle_uninstall_test/BUILD.gn index 1d5d96d8118a7b5bfcc2477b69f0ebbcad34ad4d..4b33f57d20be047c6e8d9ac60184771e6102ad69 100755 --- a/services/test/moduletest/common/bms/bundle_uninstall_test/BUILD.gn +++ b/services/test/moduletest/common/bms/bundle_uninstall_test/BUILD.gn @@ -32,6 +32,7 @@ ohos_moduletest("BmsBundleUninstallerModuleTest") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include/bundlemgr", "//third_party/json/include", "${services_path}/test/mock/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -45,6 +46,9 @@ ohos_moduletest("BmsBundleUninstallerModuleTest") { "${services_path}/bundlemgr/src/installd/installd_host_impl.cpp", "${services_path}/bundlemgr/src/installd/installd_operator.cpp", "${services_path}/bundlemgr/src/installd/installd_service.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += bundle_install_sources @@ -72,6 +76,7 @@ ohos_moduletest("BmsBundleUninstallerModuleTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ diff --git a/services/test/moduletest/common/bms/bundle_uninstall_test/bms_bundle_uninstaller_module_test.cpp b/services/test/moduletest/common/bms/bundle_uninstall_test/bms_bundle_uninstaller_module_test.cpp index 5a65a0ab728cedc641a4c3231c2ac0713ef40891..73ceee1bf75a5086dd1acaa5fe2459ff1a4aa902 100755 --- a/services/test/moduletest/common/bms/bundle_uninstall_test/bms_bundle_uninstaller_module_test.cpp +++ b/services/test/moduletest/common/bms/bundle_uninstall_test/bms_bundle_uninstaller_module_test.cpp @@ -157,7 +157,7 @@ void BmsBundleUninstallerModuleTest::CheckBundleInfoExist(const std::string bund BundleInfo info; std::shared_ptr bms = DelayedSingleton::GetInstance(); auto dataMgr = bms->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool isBundleExist = dataMgr->GetBundleInfo(bundlename, BundleFlag::GET_BUNDLE_DEFAULT, info); EXPECT_TRUE(isBundleExist); } @@ -167,7 +167,7 @@ void BmsBundleUninstallerModuleTest::CheckBundleInfoNonExist(const std::string b BundleInfo info; std::shared_ptr bms = DelayedSingleton::GetInstance(); auto dataMgr = bms->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); bool isBundleExist = dataMgr->GetBundleInfo(bundlename, BundleFlag::GET_BUNDLE_DEFAULT, info); EXPECT_FALSE(isBundleExist); } @@ -214,13 +214,13 @@ HWTEST_F(BmsBundleUninstallerModuleTest, Uninstall_0100, Function | MediumTest | { std::string bundlePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; ErrCode installResult = InstallBundle(bundlePath); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(BUNDLE_NAME); CheckBundleInfoExist(BUNDLE_NAME); ErrCode uninstallResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); CheckFileNonExist(BUNDLE_NAME); CheckBundleInfoNonExist(BUNDLE_NAME); } @@ -234,14 +234,14 @@ HWTEST_F(BmsBundleUninstallerModuleTest, Uninstall_0200, Function | MediumTest | { std::string bundlePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; ErrCode installResult = InstallBundle(bundlePath); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(BUNDLE_NAME); CheckBundleInfoExist(BUNDLE_NAME); std::string errorBundleName = "com.third.test0"; ErrCode uninstallResult = UninstallBundle(errorBundleName); - ASSERT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE); + EXPECT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE); CheckFileNonExist(errorBundleName); CheckBundleInfoNonExist(errorBundleName); @@ -256,18 +256,18 @@ HWTEST_F(BmsBundleUninstallerModuleTest, Uninstall_0300, Function | MediumTest | { std::string bundlePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; ErrCode installResult = InstallBundle(bundlePath); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(BUNDLE_NAME); CheckBundleInfoExist(BUNDLE_NAME); ErrCode uninstallResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); CheckFileNonExist(BUNDLE_NAME); CheckBundleInfoNonExist(BUNDLE_NAME); uninstallResult = UninstallBundle(BUNDLE_NAME); - ASSERT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE); + EXPECT_EQ(uninstallResult, ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE); } /** @@ -279,13 +279,13 @@ HWTEST_F(BmsBundleUninstallerModuleTest, Uninstall_0400, Function | MediumTest | { std::string bundlePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; ErrCode installResult = InstallBundle(bundlePath); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(BUNDLE_NAME); CheckBundleInfoExist(BUNDLE_NAME); ErrCode uninstallResult = UninstallHap(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); CheckFileNonExist(BUNDLE_NAME); CheckBundleInfoNonExist(BUNDLE_NAME); } @@ -299,17 +299,17 @@ HWTEST_F(BmsBundleUninstallerModuleTest, Uninstall_0500, Function | MediumTest | { std::string bundlePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1" + Constants::INSTALL_FILE_SUFFIX; ErrCode installResult = InstallBundle(bundlePath); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); bundlePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4" + Constants::INSTALL_FILE_SUFFIX; installResult = InstallBundle(bundlePath); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); CheckFileExist(BUNDLE_NAME); CheckBundleInfoExist(BUNDLE_NAME); ErrCode uninstallResult = UninstallHap(BUNDLE_NAME, MODULE_PACKAGE); - ASSERT_EQ(uninstallResult, ERR_OK); + EXPECT_EQ(uninstallResult, ERR_OK); CheckHapDirNonExist(BUNDLE_NAME, MODULE_PACKAGE); CheckFileExist(BUNDLE_NAME); CheckBundleInfoExist(BUNDLE_NAME); @@ -325,24 +325,24 @@ HWTEST_F(BmsBundleUninstallerModuleTest, Uninstall_0600, Function | MediumTest | BundleInfo info; std::shared_ptr bms = DelayedSingleton::GetInstance(); auto dataMgr = bms->GetDataMgr(); - ASSERT_NE(dataMgr, nullptr); + EXPECT_NE(dataMgr, nullptr); std::string bundlePath = THIRD_BUNDLE_PATH + "bmsThirdBundle13" + Constants::INSTALL_FILE_SUFFIX; std::string bundleName = "com.third.hiworld.example5"; ErrCode installResult = InstallBundle(bundlePath); - ASSERT_EQ(installResult, ERR_OK); + EXPECT_EQ(installResult, ERR_OK); bool isBundleExist = dataMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info); EXPECT_TRUE(isBundleExist); CheckFileExist(bundleName); CheckBundleInfoExist(bundleName); auto installer = DelayedSingleton::GetInstance()->GetBundleInstaller(); - ASSERT_NE(installer, nullptr); + EXPECT_NE(installer, nullptr); OHOS::sptr receiver = new (std::nothrow) MockStatusReceiver(); - ASSERT_NE(receiver, nullptr); + EXPECT_NE(receiver, nullptr); InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; installer->Uninstall(bundleName, installParam, receiver); - ASSERT_EQ(receiver->GetResultCode(), ERR_OK); + EXPECT_EQ(receiver->GetResultCode(), ERR_OK); isBundleExist = dataMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info); EXPECT_FALSE(isBundleExist); CheckFileNonExist(bundleName); diff --git a/services/test/moduletest/common/bms/service_start_process_test/BUILD.gn b/services/test/moduletest/common/bms/service_start_process_test/BUILD.gn index 8a8e4a39e6fa2889dacc6f4a1462d59187333227..adf376a6774db84de95a835856053994b7c76627 100755 --- a/services/test/moduletest/common/bms/service_start_process_test/BUILD.gn +++ b/services/test/moduletest/common/bms/service_start_process_test/BUILD.gn @@ -21,7 +21,10 @@ module_output_path = "appexecfwk_standard/mstbundlemgrservice" ohos_moduletest("BmsServiceStartModuleTest") { module_out_path = module_output_path - include_dirs = [ "${appexecfwk_path}/interfaces" ] + include_dirs = [ + "${appexecfwk_path}/interfaces", + "//third_party/jsoncpp/include", + ] sources = [ "${services_path}/bundlemgr/src/bundle_data_mgr.cpp", @@ -31,6 +34,9 @@ ohos_moduletest("BmsServiceStartModuleTest") { "${services_path}/bundlemgr/src/bundle_mgr_service_event_handler.cpp", "${services_path}/bundlemgr/src/bundle_scanner.cpp", "${services_path}/bundlemgr/src/bundle_status_callback_death_recipient.cpp", + "${services_path}/bundlemgr/src/kvstore_death_recipient_callback.cpp", + "${services_path}/bundlemgr/src/module_usage_data_storage.cpp", + "${services_path}/bundlemgr/src/permission_changed_death_recipient.cpp", ] sources += @@ -60,6 +66,7 @@ ohos_moduletest("BmsServiceStartModuleTest") { "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] deps += bundle_install_deps diff --git a/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestPageA.hap b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestPageA.hap new file mode 100644 index 0000000000000000000000000000000000000000..796c49737d0c7fc6b44ce4fed732505d580b5d7b Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestPageA.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestServiceB.hap b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestServiceB.hap new file mode 100644 index 0000000000000000000000000000000000000000..65fc1997d908bc8e73cf3de619fc3c2c8733e25b Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsAbilityVisibleTestServiceB.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestDFX.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestDFX.hap index 9acbceac8d2ddcec5da75a5e3167bf58018195b2..bb23b1e1c38b0b5d382d47df8b3ac737cf4e9a00 100644 Binary files a/test/resource/ams/ams_page_ability_bundle/amsSystemTestDFX.hap and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestDFX.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestQ.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestQ.hap index ccc3098085a02b578204fc26a241f6a8e1599eb6..48227ff4f4d8e6a93ab73314d69eade4c989a8db 100644 Binary files a/test/resource/ams/ams_page_ability_bundle/amsSystemTestQ.hap and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestQ.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsSystemTestR.hap b/test/resource/ams/ams_page_ability_bundle/amsSystemTestR.hap index 1bbe0c8edac9563816b83438deed6a83c888ed08..4789fee77dbe30d4c5bd26e30234f6c7750ba15b 100644 Binary files a/test/resource/ams/ams_page_ability_bundle/amsSystemTestR.hap and b/test/resource/ams/ams_page_ability_bundle/amsSystemTestR.hap differ diff --git a/test/resource/ams/ohos_test.xml b/test/resource/ams/ohos_test.xml index 00bc2c3b95707b570cafbe7c3897c49071a5ae69..3dd85bf1e07b82bc9659fba3141b3dca48d48e24 100644 --- a/test/resource/ams/ohos_test.xml +++ b/test/resource/ams/ohos_test.xml @@ -119,6 +119,12 @@ + + + + + diff --git a/test/resource/amssystemtestability/abilitySrc/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/BUILD.gn index b5090f27d3967034c753b4b9a99be78dd4e561ea..f8459bf203aa6947909c105bd20e1c27ba24082d 100644 --- a/test/resource/amssystemtestability/abilitySrc/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/BUILD.gn @@ -15,6 +15,9 @@ group("ams_system_test_app") { deps = [ "amsAbilityAppendTestA:amsAbilityAppendTestA", "amsAbilityAppendTestB:amsAbilityAppendTestB", + "amsAbilityVisibleTestPageA:amsAbilityVisibleTestPageA", + "amsAbilityVisibleTestServiceB:amsAbilityVisibleTestServiceB", + "amsConfigurationUpdatedTest:amsConfigurationUpdatedTest", "amsDataSystemTestA:amsDataSystemTestA", "amsDataSystemTestB:amsDataSystemTestB", "amsDataSystemTestC:amsDataSystemTestC", @@ -26,6 +29,8 @@ group("ams_system_test_app") { "amsKitSystemTestDataB:amsKitSystemTestDataB", "amsKitSystemTestPageA:amsKitSystemTestPageA", "amsKitSystemTestService:amsKitSystemTestService", + "amsMissionStackTest:amsMissionStackTest", + "amsMissionStackTestSubsidiary:amsMissionStackTestSubsidiary", "amsSystemTestA:amsSystemTestA", "amsSystemTestB:amsSystemTestB", "amsSystemTestC:amsSystemTestC", @@ -47,11 +52,13 @@ group("ams_system_test_app") { "amsSystemTestServiceA:amsSystemTestServiceA", "amsSystemTestServiceB:amsSystemTestServiceB", "amsSystemTestServiceC:amsSystemTestServiceC", - "amsSystemTestServiceD:amsSystemTestServiceD", + + # "amsSystemTestServiceD:amsSystemTestServiceD", "amsSystemTestServiceE:amsSystemTestServiceE", "amsSystemTestServiceF:amsSystemTestServiceF", "amsSystemTestServiceG:amsSystemTestServiceG", "amsSystemTestServiceH:amsSystemTestServiceH", + "serviceAbilityA:serviceAbilityA", "taskDispatcherTestA:taskDispatcherTestA", "taskDispatcherTestB:taskDispatcherTestB", ] diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn old mode 100644 new mode 100755 index 7212ea4c6551e7818f83f0e8ce4ee51b26be9c4b..959cca097bb82084ddf7062b7c554d1c84b2fbcd --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn @@ -29,6 +29,7 @@ config("amsAbilityAppendTestAConfig") { "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsAbilityAppendTestA\"", @@ -56,6 +57,7 @@ ohos_shared_library("amsAbilityAppendTestA") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn old mode 100644 new mode 100755 index 1dbdeec9359c42df680da5e7c22c8956fddb8120..94db70137542f2660dd2eae0ce219ccc1ed7424d --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn @@ -29,6 +29,7 @@ config("amsAbilityAppendTestBConfig") { "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsAbilityAppendTestB\"", @@ -55,6 +56,7 @@ ohos_shared_library("amsAbilityAppendTestB") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..47d0c6613f81ff009a68a58ef0ded978ea8ce16d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 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") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsAbilityVisibleTestPageAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsAbilityVisibleTestPageA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsAbilityVisibleTestPageA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea3.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpagea4.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsAbilityVisibleTestPageAConfig" ] + deps = [ + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/config.json b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b61c661241fb4d4df2d408218b6ca57d941898ff --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/config.json @@ -0,0 +1,66 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appAbilityVisiblePageA", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestR.src", + "name":"AmsSystemTestR", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsAbilityVisibleTestPageA1", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestPageA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestPageA2", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestPageA2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsAbilityVisibleTestPageA3", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestPageA3 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestPageA4", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestPageA4 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page" + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea1.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea1.h new file mode 100644 index 0000000000000000000000000000000000000000..6a0f71a49c884ec6d82c6e06b606ea47eef3137e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea1.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBLE_TEST_PAGE_A1_ +#define _AMS_ABILITY_VISIBLE_TEST_PAGE_A1_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageA1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBLE_TEST_PAGE_A1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h new file mode 100644 index 0000000000000000000000000000000000000000..dbcc4d31dbde5011a40de9a245d59bfb2f7a991b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBLE_TEST_PAGE_A2_ +#define _AMS_ABILITY_VISIBLE_TEST_PAGE_A2_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "want_agent_helper.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; +using namespace OHOS::Notification::WantAgent; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class PendingWantCallback : public CompletedCallback { +private: + /* data */ +public: + PendingWantCallback() = default; + ~PendingWantCallback() = default; + + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override + { + STPageAbilityEvent::PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_triggerWantAgentState); + } +}; + +class AmsAbilityVisibleTestPageA2 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void GetAndTriggerWantAgent(std::string type, Want want, WantAgentConstant::OperationType operationType); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBLE_TEST_PAGE_A2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea3.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea3.h new file mode 100644 index 0000000000000000000000000000000000000000..e92e1735f2574b3012286e9434ab7052076ad86d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea3.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBLE_TEST_PAGE_A3_ +#define _AMS_ABILITY_VISIBLE_TEST_PAGE_A3_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageA3 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBLE_TEST_PAGE_A3_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea4.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea4.h new file mode 100644 index 0000000000000000000000000000000000000000..2b3591cb5129bbb65ac4d9a43b564fa3f59b7166 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea4.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBLE_TEST_PAGE_A4_ +#define _AMS_ABILITY_VISIBLE_TEST_PAGE_A4_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageA4 : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBLE_TEST_PAGE_A4_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b54bb086d55ed747d90d7c4cd0db86f2705069c1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestpagea1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageA1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::Init"); + Ability::Init(abilityInfo, application, handler, token); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); +} + +void AmsAbilityVisibleTestPageA1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageA1::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want, 1); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA1::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA1::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1dd32126b946cda35b2ac232d21b8b27e6e43d00 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestpagea2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageA2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::Init"); + Ability::Init(abilityInfo, application, handler, token); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); +} + +void AmsAbilityVisibleTestPageA2::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageA2::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + if (startAbilityType == "TriggerWantAgentPageAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_ABILITY); + } + if (startAbilityType == "TriggerWantAgentServiceAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_SERVICE); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA2::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA2::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA2::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void AmsAbilityVisibleTestPageA2::GetAndTriggerWantAgent( + std::string type, Want want, WantAgentConstant::OperationType operationType) +{ + std::vector> vec; + std::shared_ptr wantParameter = std::make_shared(want); + vec.push_back(wantParameter); + WantAgentInfo info(0, operationType, WantAgentConstant::Flags::UPDATE_PRESENT_FLAG, vec, nullptr); + APP_LOGI("AmsAbilityVisibleTestPageA2::StartOtherAbility()"); + std::shared_ptr agent = WantAgentHelper::GetWantAgent(GetContext(), info); + if (agent == nullptr) { + pageAbilityEvent.PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_getWantAgentState); + APP_LOGI("AmsAbilityVisibleTestPageA2::StartOtherAbility():GetWantAgent is nullptr."); + return; + } + TriggerInfo paramsInfo; + std::shared_ptr callback = std::make_shared(); + WantAgentHelper::TriggerWantAgent(GetContext(), agent, callback, paramsInfo); + APP_LOGI("AmsAbilityVisibleTestPageA2::StartOtherAbility():WantAgentHelper::TriggerWantAgent end."); +} + +REGISTER_AA(AmsAbilityVisibleTestPageA2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a041eb3f6e44221064dc13fa106cf7c0befe6ba --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestpagea3.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageA3::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageA3::onStart"); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA3::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA3::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA3::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA3::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageA3); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22816749749d1e9e1a705d255b7bba96f06550e1 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestpagea4.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageA4::OnStart(const Want &want) +{ + GetWantInfo(want); + + APP_LOGI("AmsAbilityVisibleTestPageA4::onStart"); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageA4::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageA4::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageA4::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageA4::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageA4); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4985c58073318cad1478ccb0cd79d16f6902c2d0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2021 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") +SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB" +SUBST_TOOLS_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/tools" +config("amsAbilityVisibleTestServiceBConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsAbilityVisibleTestServiceB\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsAbilityVisibleTestServiceB") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestdata.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpageb1.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestpageb2.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestservice.cpp", + "${SUBDEMOSYSTEM_DIR}/src/amsabilityvisibletestservicea1.cpp", + "${SUBST_TOOLS_DIR}/src/stpageabilityevent.cpp", + ] + configs = [ ":amsAbilityVisibleTestServiceBConfig" ] + deps = [ + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/config.json b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d3fd75a750958b75e04e31fdd10b9610428b1b6e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/config.json @@ -0,0 +1,77 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.appAbilityVisibleServiceB", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.hos.AmsSystemTestR.src", + "name":"AmsSystemTestR", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "AmsAbilityVisibleTestPageB1", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestPageB1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestPageB2", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestPageB2 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "AmsAbilityVisibleTestData", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestData Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "data", + "visible": false, + "uri":"dataability://com.ohos.amsst.appAbilityVisibleServiceB.AmsAbilityVisibleTestData" + }, + { + "name": "AmsAbilityVisibleTestService", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestService Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": false + }, + { + "name": "AmsAbilityVisibleTestServiceA1", + "icon": "$media:snowball", + "label": "AmsAbilityVisibleTestServiceA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": false + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestdata.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestdata.h new file mode 100644 index 0000000000000000000000000000000000000000..642ee7094ff4b39d7e59f9a507109e6a814ec74b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestdata.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBALE_TEST_DATA_ +#define _AMS_ABILITY_VISIBALE_TEST_DATA_ +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { + +class AmsAbilityVisibleTestData : public Ability { +public: + ~AmsAbilityVisibleTestData(); + +protected: + virtual void OnStart(const Want &want) override; + virtual int Insert(const Uri &uri, const ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) override; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual int OpenFile(const Uri &uri, const std::string &mode) override; + +private: + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBALE_TEST_DATA_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb1.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb1.h new file mode 100644 index 0000000000000000000000000000000000000000..c3770c369f7e9f079e126317bb95b7230156e93d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb1.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBLE_TEST_PAGE_B1_ +#define _AMS_ABILITY_VISIBLE_TEST_PAGE_B1_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestPageB1 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBLE_TEST_PAGE_B1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h new file mode 100644 index 0000000000000000000000000000000000000000..9fe69a30b9d65c3e3e7da6dd1c4aacb555352d64 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBLE_TEST_PAGE_B2_ +#define _AMS_ABILITY_VISIBLE_TEST_PAGE_B2_ +#include "stpageabilityevent.h" +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "want_agent_helper.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; +using namespace OHOS::Notification::WantAgent; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class PendingWantCallback : public CompletedCallback { +private: + /* data */ +public: + PendingWantCallback() = default; + ~PendingWantCallback() = default; + + virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override + { + STPageAbilityEvent::PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_triggerWantAgentState); + } +}; + +class AmsAbilityVisibleTestPageB2 : public Ability { +protected: + virtual void Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + void GetAndTriggerWantAgent(std::string type, Want want, WantAgentConstant::OperationType operationType); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + sptr stub_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBLE_TEST_PAGE_B2_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservice.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservice.h new file mode 100644 index 0000000000000000000000000000000000000000..e4d98340dc939a7dc8e9268afab8f0dd13cb17f6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservice.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBALE_TEST_SERVICE_ +#define _AMS_ABILITY_VISIBALE_TEST_SERVICE_ +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestService : public Ability { +public: + ~AmsAbilityVisibleTestService(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBALE_TEST_SERVICE_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservicea1.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservicea1.h new file mode 100644 index 0000000000000000000000000000000000000000..d95a60172e4f72697df7b12ebe73b746cf09364d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservicea1.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 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 _AMS_ABILITY_VISIBALE_TEST_SERVICE_A1_ +#define _AMS_ABILITY_VISIBALE_TEST_SERVICE_A1_ +#include "stpageabilityevent.h" +#include +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; + +class AbilityConnectCallback : public AbilityConnectionStub { +public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityConnectDone:resultCode = %{public}d", resultCode); + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + APP_LOGI("AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = %{public}d", resultCode); + } +}; + +class AmsAbilityVisibleTestServiceA1 : public Ability { +public: + ~AmsAbilityVisibleTestServiceA1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::string Split(std::string &str, std::string delim); + + std::string targetType_; + std::string targetBundle_; + std::string targetAbility_; + STPageAbilityEvent pageAbilityEvent; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // _AMS_ABILITY_VISIBALE_TEST_SERVICE_A1_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestdata.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestdata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..624298a0ee79f40447199239e3b400396dc7eee0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestdata.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestdata.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { + +const static int defenvntCode = 1; + +AmsAbilityVisibleTestData::~AmsAbilityVisibleTestData() +{} + +void AmsAbilityVisibleTestData::OnStart(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestData::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +int AmsAbilityVisibleTestData::Insert(const Uri &uri, const ValuesBucket &value) +{ + APP_LOGI("AmsAbilityVisibleTestData::Insert"); + int result = Ability::Insert(uri, value); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInsert; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +int AmsAbilityVisibleTestData::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsAbilityVisibleTestData::Delete"); + int result = Ability::Delete(uri, predicates); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateDelete; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +int AmsAbilityVisibleTestData::Update( + const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsAbilityVisibleTestData::Update"); + int result = Ability::Update(uri, value, predicates); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateUpdate; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +std::shared_ptr AmsAbilityVisibleTestData::Query( + const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +{ + APP_LOGI("AmsAbilityVisibleTestData::Query"); + std::shared_ptr result = Ability::Query(uri, columns, predicates); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateQuery; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +std::vector AmsAbilityVisibleTestData::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("AmsAbilityVisibleTestData::GetFileTypes"); + std::vector result = Ability::GetFileTypes(uri, mimeTypeFilter); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateGetFileTypes; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +int AmsAbilityVisibleTestData::OpenFile(const Uri &uri, const std::string &mode) +{ + APP_LOGI("AmsAbilityVisibleTestData::OpenFile"); + int result = Ability::OpenFile(uri, mode); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOpenFile; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, defenvntCode, eventData); + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestData); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3ab87e077f7acef41090264caecca2285d7a8e7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestpageb1.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageB1::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::Init"); + Ability::Init(abilityInfo, application, handler, token); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); +} + +void AmsAbilityVisibleTestPageB1::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageB1::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnActive"); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageB1::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB1::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageB1::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageB1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestPageB1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2caba9013d0579c77da46623421b7e3049325ce2 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestpageb2.h" + +namespace OHOS { +namespace AppExecFwk { +void AmsAbilityVisibleTestPageB2::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::Init"); + Ability::Init(abilityInfo, application, handler, token); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateInit; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, eventData); + stub_ = (new (std::nothrow) AbilityConnectCallback()); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this(), stub_); +} + +void AmsAbilityVisibleTestPageB2::OnStart(const Want &want) +{ + GetWantInfo(want); + APP_LOGI("AmsAbilityVisibleTestPageB2::onStart"); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnForeground(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnForegroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::onStop"); + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnActive"); + Ability::OnActive(); + Ability::OnActive(); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want want; + want.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + want.SetParam("targetBundle", targetBundle_); + want.SetParam("targetAbility", targetAbility_); + want.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(want); + } + if (startAbilityType == "Service") { + if (stub_) { + ConnectAbility(want, stub_); + } + } + if (startAbilityType == "Data" || startAbilityType == "DataRelease") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + if (startAbilityType == "DataRelease") { + helper->Release(); + } + } + if (startAbilityType == "TriggerWantAgentPageAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_ABILITY); + } + if (startAbilityType == "TriggerWantAgentServiceAbility") { + GetAndTriggerWantAgent(startAbilityType, want, WantAgentConstant::OperationType::START_SERVICE); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestPageB2::OnBackground"); + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +void AmsAbilityVisibleTestPageB2::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestPageB2::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestPageB2::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +void AmsAbilityVisibleTestPageB2::GetAndTriggerWantAgent( + std::string type, Want want, WantAgentConstant::OperationType operationType) +{ + std::vector> vec; + std::shared_ptr wantParameter = std::make_shared(want); + vec.push_back(wantParameter); + WantAgentInfo info(0, operationType, WantAgentConstant::Flags::UPDATE_PRESENT_FLAG, vec, nullptr); + APP_LOGI("AmsAbilityVisibleTestPageB2::StartOtherAbility()"); + std::shared_ptr agent = WantAgentHelper::GetWantAgent(GetContext(), info); + if (agent == nullptr) { + pageAbilityEvent.PublishEvent( + STEventName::g_eventName, STEventName::g_defeventCode, STEventName::g_getWantAgentState); + APP_LOGI("AmsAbilityVisibleTestPageB2::StartOtherAbility():GetWantAgent is nullptr."); + return; + } + TriggerInfo paramsInfo; + std::shared_ptr callback = std::make_shared(); + WantAgentHelper::TriggerWantAgent(GetContext(), agent, callback, paramsInfo); + APP_LOGI("AmsAbilityVisibleTestPageB2::StartOtherAbility():WantAgentHelper::TriggerWantAgent end."); +} + +REGISTER_AA(AmsAbilityVisibleTestPageB2); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4ee376ae8f281ad5f7d0f8abb3d4a80afc38d78 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestservice.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { + +AmsAbilityVisibleTestService::~AmsAbilityVisibleTestService() +{} + +void AmsAbilityVisibleTestService::OnStart(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnCommand"); + + Ability::OnCommand(want, restart, startId); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnNewWant"); + + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnStop"); + + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnActive"); + + Ability::OnActive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnInactive"); + + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestService::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestService::OnBackground"); + + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +sptr AmsAbilityVisibleTestService::OnConnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnConnect"); + + sptr ret = Ability::OnConnect(want); + GetWantInfo(want); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want wantOther; + wantOther.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + wantOther.SetParam("targetBundle", targetBundle_); + wantOther.SetParam("targetAbility", targetAbility_); + wantOther.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(wantOther); + } + if (startAbilityType == "Service") { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + ConnectAbility(wantOther, stub); + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnConnectCount(), eventData); + return ret; +} + +void AmsAbilityVisibleTestService::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestService::OnDisconnect"); + + Ability::OnDisconnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnDisconnectCount(), eventData); +} + +void AmsAbilityVisibleTestService::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestService::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestService::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestService); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..208056c5250385a7970fe6fa753c02aa120e8fdb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2021 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 "amsabilityvisibletestservicea1.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { + +AmsAbilityVisibleTestServiceA1::~AmsAbilityVisibleTestServiceA1() +{} + +void AmsAbilityVisibleTestServiceA1::OnStart(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnStart"); + pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); + Ability::OnStart(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnCommand"); + + Ability::OnCommand(want, restart, startId); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnNewWant(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnNewWant"); + + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnStop() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnStop"); + + Ability::OnStop(); + pageAbilityEvent.UnsubscribeEvent(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStop; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnActive() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnActive"); + + Ability::OnActive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnInactive() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnInactive"); + + Ability::OnInactive(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::OnBackground() +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnBackground"); + + Ability::OnBackground(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); +} + +sptr AmsAbilityVisibleTestServiceA1::OnConnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnConnect"); + + sptr ret = Ability::OnConnect(want); + GetWantInfo(want); + std::string startBundleName = this->Split(targetBundle_, ","); + std::string startAbilityName = this->Split(targetAbility_, ","); + std::string startAbilityType = this->Split(targetType_, ","); + if (!startBundleName.empty() && !startAbilityName.empty() && !startAbilityType.empty()) { + Want wantOther; + wantOther.SetElementName(startBundleName, startAbilityName); + if (!targetBundle_.empty() && !targetAbility_.empty() && !targetType_.empty()) { + wantOther.SetParam("targetBundle", targetBundle_); + wantOther.SetParam("targetAbility", targetAbility_); + wantOther.SetParam("type", targetType_); + } + if (startAbilityType == "Page") { + StartAbility(wantOther); + } + if (startAbilityType == "Service") { + sptr stub(new (std::nothrow) AbilityConnectCallback()); + ConnectAbility(wantOther, stub); + } + if (startAbilityType == "Data") { + Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); + std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); + AppExecFwk::ValuesBucket bucket; + helper->Insert(dataAbilityUri, bucket); + } + } + Clear(); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnConnectCount(), eventData); + return ret; +} + +void AmsAbilityVisibleTestServiceA1::OnDisconnect(const Want &want) +{ + APP_LOGI("AmsAbilityVisibleTestServiceA1::OnDisconnect"); + + Ability::OnDisconnect(want); + std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; + pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnDisconnectCount(), eventData); +} + +void AmsAbilityVisibleTestServiceA1::Clear() +{ + targetType_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; +} + +void AmsAbilityVisibleTestServiceA1::GetWantInfo(const Want &want) +{ + Want mWant(want); + targetType_ = mWant.GetStringParam("type"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); +} + +std::string AmsAbilityVisibleTestServiceA1::Split(std::string &str, std::string delim) +{ + std::string result; + if (!str.empty()) { + size_t index = str.find(delim); + if (index != std::string::npos) { + result = str.substr(0, index); + str = str.substr(index + delim.size()); + } else { + result = str; + str = ""; + } + } + return result; +} + +REGISTER_AA(AmsAbilityVisibleTestServiceA1); +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..66d3be7c6a03b916d99300906b819aa69f110fa6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsConfigurationUpdatedTestConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${kits_path}/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsConfigurationUpdatedTest\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsConfigurationUpdatedTest") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/fifth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/fourth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/sixth_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + "${SUBDEMOSYSTEM_DIR}/src/third_ability.cpp", + ] + configs = [ ":amsConfigurationUpdatedTestConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${kits_path}:appkit_native", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/config.json b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..6c7fb51531ce873ff33f5e51de360a36e8a93b10 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/config.json @@ -0,0 +1,92 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.ConfigurationUpdated", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.ConfigurationUpdated.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "label": "MainAbility label", + "launchType": "standard", + "configChanges": ["orientation"], + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowball", + "label": "SecondAbility label", + "launchType": "standard", + "configChanges": ["orientation","locale"], + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ThirdAbility", + "icon": "$media:snowball", + "label": "ThirdAbility label", + "launchType": "standard", + "configChanges": ["orientation","locale","layout"], + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "FourthAbility", + "icon": "$media:snowball", + "label": "FourthAbility label", + "launchType": "standard", + "configChanges": ["orientation","locale","layout","fontSize"], + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "FifthAbility", + "icon": "$media:snowball", + "label": "FifthAbility label", + "launchType": "standard", + "configChanges": ["orientation","locale","layout","fontSize","density"], + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "SixthAbility", + "icon": "$media:snowball", + "label": "SixthAbility label", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fifth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fifth_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..b1ae960611e42037a4dfee69a4da9c612c1290b3 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fifth_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 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 AMS_CONFIGURATION_UPDATED_TEST_FIFTH_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_FIFTH_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" +//#include "aafwk_dummy_configuration.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FifthAbilityEventSubscriber; +class FifthAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + // void MissionStackcase1(int code); + // void MissionStackcase2(int code); + + FifthAbility() + { + mapCase_ = { + // {(int)MissionStackApi::LockMission, + // { + // [this](int code) { MissionStackcase1(code); }, + // [this](int code) { MissionStackcase2(code); }, + // }}, + }; + } + + std::unordered_map>> mapCase_; + ~FifthAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class FifthAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FifthAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + //{"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + fifthAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + fifthAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + FifthAbility *fifthAbility; + std::unordered_map> mapTestFunc_; + ~FifthAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_FIFTH_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fourth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fourth_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..7b4267e9702615a4e0d25b98b292e9f0eb2493d5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fourth_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 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 AMS_CONFIGURATION_UPDATED_TEST_FOURTH_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_FOURTH_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" +//#include "aafwk_dummy_configuration.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FourthAbilityEventSubscriber; +class FourthAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + // void MissionStackcase1(int code); + // void MissionStackcase2(int code); + + FourthAbility() + { + mapCase_ = { + // {(int)MissionStackApi::LockMission, + // { + // [this](int code) { MissionStackcase1(code); }, + // [this](int code) { MissionStackcase2(code); }, + // }}, + }; + } + + std::unordered_map>> mapCase_; + ~FourthAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class FourthAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FourthAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + //{"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + fourthAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + fourthAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + FourthAbility *fourthAbility; + std::unordered_map> mapTestFunc_; + ~FourthAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_FOURTH_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..bfd98dd854da458a1a8fcb36bc10c5f91f53e631 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/main_ability.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 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 AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" +//#include "aafwk_dummy_configuration.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class MainAbilityEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + // void MissionStackcase1(int code); + // void MissionStackcase2(int code); + + MainAbility() + { + mapCase_ = { + // {(int)MissionStackApi::LockMission, + // { + // [this](int code) { MissionStackcase1(code); }, + // [this](int code) { MissionStackcase2(code); }, + // }}, + }; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + std::string callbackSeq; + std::string callbackUpdated; +}; +class MainAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit MainAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + //{"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~MainAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_FIRST_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..b6488172c50631852622a1ca9a78c4e0d8271158 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/second_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 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 AMS_CONFIGURATION_UPDATED_TEST_SECOND_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" +//#include "aafwk_dummy_configuration.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondAbilityEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void MissionStackcase1(int code); + void MissionStackcase2(int code); + + SecondAbility() + { + mapCase_ = { + // {(int)MissionStackApi::LockMission, + // { + // [this](int code) { MissionStackcase1(code); }, + // [this](int code) { MissionStackcase2(code); }, + // }}, + }; + } + + std::unordered_map>> mapCase_; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class SecondAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + //{"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + secondAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + secondAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *secondAbility; + std::unordered_map> mapTestFunc_; + ~SecondAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/sixth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/sixth_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..f8e3df1a03152865ab31f151b684c91917c91b12 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/sixth_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 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 AMS_CONFIGURATION_UPDATED_TEST_SIXTH_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_SIXTH_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" +//#include "aafwk_dummy_configuration.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SixthAbilityEventSubscriber; +class SixthAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + // void MissionStackcase1(int code); + // void MissionStackcase2(int code); + + SixthAbility() + { + mapCase_ = { + // {(int)MissionStackApi::LockMission, + // { + // [this](int code) { MissionStackcase1(code); }, + // [this](int code) { MissionStackcase2(code); }, + // }}, + }; + } + + std::unordered_map>> mapCase_; + ~SixthAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class SixthAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SixthAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + //{"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + sixthAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + sixthAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SixthAbility *sixthAbility; + std::unordered_map> mapTestFunc_; + ~SixthAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_SIXTH_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/third_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..c83fcd2bf001c0bd03d9171f55e729344caed795 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/third_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 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 AMS_CONFIGURATION_UPDATED_TEST_THIRD_ABILITY_H +#define AMS_CONFIGURATION_UPDATED_TEST_THIRD_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" +//#include "aafwk_dummy_configuration.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class ThirdAbilityEventSubscriber; +class ThirdAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + // void MissionStackcase1(int code); + // void MissionStackcase2(int code); + + ThirdAbility() + { + mapCase_ = { + // {(int)MissionStackApi::LockMission, + // { + // [this](int code) { MissionStackcase1(code); }, + // [this](int code) { MissionStackcase2(code); }, + // }}, + }; + } + + std::unordered_map>> mapCase_; + ~ThirdAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class ThirdAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit ThirdAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + //{"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + thirdAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + thirdAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + ThirdAbility *thirdAbility; + std::unordered_map> mapTestFunc_; + ~ThirdAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_CONFIGURATION_UPDATED_TEST_THIRD_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fifth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fifth_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2676b3941f2a49525369231bb1d63c73ee4b74d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fifth_ability.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021 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 "fifth_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void FifthAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FifthAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +FifthAbility::~FifthAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void FifthAbility::OnStart(const Want &want) +{ + APP_LOGI("FifthAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH_LIFECYCLE, FIFTH_ABILITY_CODE, "OnStart"); +} + +void FifthAbility::OnStop() +{ + APP_LOGI("FifthAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH_LIFECYCLE, FIFTH_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void FifthAbility::OnActive() +{ + APP_LOGI("FifthAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; //OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH_LIFECYCLE, FIFTH_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void FifthAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("FifthAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH_LIFECYCLE, FIFTH_ABILITY_CODE, callbackUpdated); +} + +void FifthAbility::OnInactive() +{ + APP_LOGI("FifthAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH_LIFECYCLE, FIFTH_ABILITY_CODE, "OnInactive"); +} + +void FifthAbility::OnBackground() +{ + APP_LOGI("FifthAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH_LIFECYCLE, FIFTH_ABILITY_CODE, "OnBackground"); +} + +void FifthAbility::OnForeground(const Want &want) +{ + APP_LOGI("FifthAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_FIFTH_LIFECYCLE, FIFTH_ABILITY_CODE, "OnForeground"); +} + +void FifthAbility::SubscribeEvent() +{ + std::vector eventList = { + //g_EVENT_REQU_FIFTH, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->fifthAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FifthAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FifthAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FifthAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FifthAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + // if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIFTH.c_str()) == 0) { + // auto target = data.GetData(); + // auto caseInfo = TestUtils::split(target, "_"); + // if (caseInfo.size() < 3) { + // return; + // } + // if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + // mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + // } else { + // APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + // } + // } +} + +void FifthAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("FifthAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// void FifthAbility::MissionStackcase1(int code) +// { +// APP_LOGI("FifthAbility::MissionStackcase1====<"); +// bool result = true; +// result = true; +// const std::shared_ptr dcf = std::make_shared("orientation"); +// unsigned int flag = dcf->Differ(dcf); +// APP_LOGI("FifthAbility::MissionStackcase1==flag====>%{public}d",flag); +// Configuration configuration; +// std::string configName = configuration.GetName(); +// APP_LOGI("FifthAbility::MissionStackcase1==configName====>%{public}s",configName.c_str()); +// //configuration.getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE); +// //configuration.UpdateConfiguration(dcf); + +// //TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +// } + +// void FifthAbility::MissionStackcase2(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); +// TerminateAbility(); +// } + + +REGISTER_AA(FifthAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fourth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fourth_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49694b6af7126476ec252b059c8ae3fc08f701c2 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fourth_ability.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021 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 "fourth_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void FourthAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("FourthAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +FourthAbility::~FourthAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void FourthAbility::OnStart(const Want &want) +{ + APP_LOGI("FourthAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_FOURTH_LIFECYCLE, FOURTH_ABILITY_CODE, "OnStart"); +} + +void FourthAbility::OnStop() +{ + APP_LOGI("FourthAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_FOURTH_LIFECYCLE, FOURTH_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void FourthAbility::OnActive() +{ + APP_LOGI("FourthAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; //OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_FOURTH_LIFECYCLE, FOURTH_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void FourthAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("FourthAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_FOURTH_LIFECYCLE, FOURTH_ABILITY_CODE, callbackUpdated); +} + +void FourthAbility::OnInactive() +{ + APP_LOGI("FourthAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_FOURTH_LIFECYCLE, FOURTH_ABILITY_CODE, "OnInactive"); +} + +void FourthAbility::OnBackground() +{ + APP_LOGI("FourthAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_FOURTH_LIFECYCLE, FOURTH_ABILITY_CODE, "OnBackground"); +} + +void FourthAbility::OnForeground(const Want &want) +{ + APP_LOGI("FourthAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_FOURTH_LIFECYCLE, FOURTH_ABILITY_CODE, "OnForeground"); +} + +void FourthAbility::SubscribeEvent() +{ + std::vector eventList = { + //g_EVENT_REQU_FOURTH, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->fourthAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FourthAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FourthAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FourthAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FourthAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + // if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FOURTH.c_str()) == 0) { + // auto target = data.GetData(); + // auto caseInfo = TestUtils::split(target, "_"); + // if (caseInfo.size() < 3) { + // return; + // } + // if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + // mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + // } else { + // APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + // } + // } +} + +void FourthAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("FourthAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// void FourthAbility::MissionStackcase1(int code) +// { +// APP_LOGI("FourthAbility::MissionStackcase1====<"); +// bool result = true; +// result = true; +// const std::shared_ptr dcf = std::make_shared("orientation"); +// unsigned int flag = dcf->Differ(dcf); +// APP_LOGI("FourthAbility::MissionStackcase1==flag====>%{public}d",flag); +// Configuration configuration; +// std::string configName = configuration.GetName(); +// APP_LOGI("FourthAbility::MissionStackcase1==configName====>%{public}s",configName.c_str()); +// //configuration.getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE); +// //configuration.UpdateConfiguration(dcf); + +// //TestUtils::PublishEvent(g_EVENT_RESP_FOURTH, code, std::to_string(result)); +// } + +// void FourthAbility::MissionStackcase2(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_FOURTH, code, std::to_string(result)); +// TerminateAbility(); +// } + + +REGISTER_AA(FourthAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ceca34cd9bf57c2fc90d21fcdf831e70d0b84b8c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/main_ability.cpp @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2021 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; //OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("MainAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, callbackUpdated); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnForeground"); +} + + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + //g_EVENT_REQU_MAIN, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void MainAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + // if (std::strcmp(eventName.c_str(), g_EVENT_REQU_MAIN.c_str()) == 0) { + // auto target = data.GetData(); + // auto caseInfo = TestUtils::split(target, "_"); + // if (caseInfo.size() < 3) { + // return; + // } + // if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + // mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + // } else { + // APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + // } + // } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + + +// void MainAbility::MissionStackcase1(int code) +// { +// APP_LOGI("MainAbility::MissionStackcase1====<"); +// bool result = true; +// result = true; +// const std::shared_ptr dcf = std::make_shared("orientation"); +// unsigned int flag = dcf->Differ(dcf); +// APP_LOGI("MainAbility::MissionStackcase1==flag====>%{public}d",flag); +// Configuration configuration; +// std::string configName = configuration.GetName(); +// APP_LOGI("MainAbility::MissionStackcase1==configName====>%{public}s",configName.c_str()); +// //configuration.getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE); +// //configuration.UpdateConfiguration(dcf); + +// TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +// } + +// void MainAbility::MissionStackcase2(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +// TerminateAbility(); +// } + + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26a63658875b225b0cb2f68504b3d6afd036959d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/second_ability.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; //OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("SecondAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, callbackUpdated); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnForeground"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + //g_EVENT_REQU_SECOND, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->secondAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + // if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + // auto target = data.GetData(); + // auto caseInfo = TestUtils::split(target, "_"); + // if (caseInfo.size() < 3) { + // return; + // } + // if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + // mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + // } else { + // APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + // } + // } +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// void SecondAbility::MissionStackcase1(int code) +// { +// APP_LOGI("SecondAbility::MissionStackcase1====<"); +// bool result = true; +// result = true; +// const std::shared_ptr dcf = std::make_shared("orientation"); +// unsigned int flag = dcf->Differ(dcf); +// APP_LOGI("SecondAbility::MissionStackcase1==flag====>%{public}d",flag); +// Configuration configuration; +// std::string configName = configuration.GetName(); +// APP_LOGI("SecondAbility::MissionStackcase1==configName====>%{public}s",configName.c_str()); +// //configuration.getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE); +// //configuration.UpdateConfiguration(dcf); + +// //TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +// } + +// void SecondAbility::MissionStackcase2(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +// TerminateAbility(); +// } + + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/sixth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/sixth_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45c8a2597c97bdfd70dff6ae64d56e346226a266 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/sixth_ability.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2021 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 "sixth_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void SixthAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SixthAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SixthAbility::~SixthAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SixthAbility::OnStart(const Want &want) +{ + APP_LOGI("SixthAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_SIXTH_LIFECYCLE, SIXTH_ABILITY_CODE, "OnStart"); +} + +void SixthAbility::OnStop() +{ + APP_LOGI("SixthAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + TestUtils::PublishEvent(g_EVENT_RESP_SIXTH_LIFECYCLE, SIXTH_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void SixthAbility::OnActive() +{ + APP_LOGI("SixthAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; //OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_SIXTH_LIFECYCLE, SIXTH_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void SixthAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("SixthAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + TestUtils::PublishEvent(g_EVENT_RESP_SIXTH_LIFECYCLE, SIXTH_ABILITY_CODE, "OnConfigurationUpdated"); +} + +void SixthAbility::OnInactive() +{ + APP_LOGI("SixthAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_SIXTH_LIFECYCLE, SIXTH_ABILITY_CODE, "OnInactive"); +} + +void SixthAbility::OnBackground() +{ + APP_LOGI("SixthAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_SIXTH_LIFECYCLE, SIXTH_ABILITY_CODE, "OnBackground"); +} + +void SixthAbility::OnForeground(const Want &want) +{ + APP_LOGI("SixthAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_SIXTH_LIFECYCLE, SIXTH_ABILITY_CODE, "OnForeground"); +} + +void SixthAbility::SubscribeEvent() +{ + std::vector eventList = { + //g_EVENT_REQU_SIXTH, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->sixthAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SixthAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SixthAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SixthAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SixthAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + // if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SIXTH.c_str()) == 0) { + // auto target = data.GetData(); + // auto caseInfo = TestUtils::split(target, "_"); + // if (caseInfo.size() < 3) { + // return; + // } + // if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + // mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + // } else { + // APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + // } + // } +} + +void SixthAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SixthAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// void SixthAbility::MissionStackcase1(int code) +// { +// APP_LOGI("SixthAbility::MissionStackcase1====<"); +// bool result = true; +// result = true; +// const std::shared_ptr dcf = std::make_shared("orientation"); +// unsigned int flag = dcf->Differ(dcf); +// APP_LOGI("SixthAbility::MissionStackcase1==flag====>%{public}d",flag); +// Configuration configuration; +// std::string configName = configuration.GetName(); +// APP_LOGI("SixthAbility::MissionStackcase1==configName====>%{public}s",configName.c_str()); +// //configuration.getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE); +// //configuration.UpdateConfiguration(dcf); + +// //TestUtils::PublishEvent(g_EVENT_RESP_SIXTH, code, std::to_string(result)); +// } + +// void SixthAbility::MissionStackcase2(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_SIXTH, code, std::to_string(result)); +// TerminateAbility(); +// } + + +REGISTER_AA(SixthAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07ebf00c47128276f0e83d0aa5783fec0a417147 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/test_utils.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg{delim}; + return std::vector{ + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/third_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/third_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3fac41b224d11508ca2c6b9018fe85b563da31c7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/third_ability.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021 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 "third_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void ThirdAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("ThirdAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +ThirdAbility::~ThirdAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ThirdAbility::OnStart(const Want &want) +{ + APP_LOGI("ThirdAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnStart"); +} + +void ThirdAbility::OnStop() +{ + APP_LOGI("ThirdAbility::OnStop"); + Ability::OnStop(); + callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void ThirdAbility::OnActive() +{ + APP_LOGI("ThirdAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; //OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void ThirdAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("ThirdAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackUpdated); +} + +void ThirdAbility::OnInactive() +{ + APP_LOGI("ThirdAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnInactive"); +} + +void ThirdAbility::OnBackground() +{ + APP_LOGI("ThirdAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnBackground"); +} + +void ThirdAbility::OnForeground(const Want &want) +{ + APP_LOGI("ThirdAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnForeground"); +} + +void ThirdAbility::SubscribeEvent() +{ + std::vector eventList = { + //g_EVENT_REQU_THIRD, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->thirdAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ThirdAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + // if (std::strcmp(eventName.c_str(), g_EVENT_REQU_THIRD.c_str()) == 0) { + // auto target = data.GetData(); + // auto caseInfo = TestUtils::split(target, "_"); + // if (caseInfo.size() < 3) { + // return; + // } + // if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + // mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + // } else { + // APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + // } + // } +} + +void ThirdAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("ThirdAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// void ThirdAbility::MissionStackcase1(int code) +// { +// APP_LOGI("ThirdAbility::MissionStackcase1====<"); +// bool result = true; +// result = true; +// const std::shared_ptr dcf = std::make_shared("orientation"); +// unsigned int flag = dcf->Differ(dcf); +// APP_LOGI("ThirdAbility::MissionStackcase1==flag====>%{public}d",flag); +// Configuration configuration; +// std::string configName = configuration.GetName(); +// APP_LOGI("ThirdAbility::MissionStackcase1==configName====>%{public}s",configName.c_str()); +// //configuration.getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE); +// //configuration.UpdateConfiguration(dcf); + +// //TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +// } + +// void ThirdAbility::MissionStackcase2(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +// TerminateAbility(); +// } + + +REGISTER_AA(ThirdAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn old mode 100644 new mode 100755 index 67ea8c33d3035e96e7fdd7265ea59243031c6cc9..901930e78c5f561df13734ef94c74c59e2b41e69 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn @@ -29,6 +29,7 @@ config("amsDataSystemTestAConfig") { "${common_path}/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsDataSystemTestA\"", @@ -57,6 +58,7 @@ ohos_shared_library("amsDataSystemTestA") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn old mode 100644 new mode 100755 index 1c95a8a84fa6f15b275703e1d314025e9583547d..0397152f27eb6d55345a486ae357e1a42e7b7c07 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn @@ -28,6 +28,7 @@ config("amsDataSystemTestBConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsDataSystemTestB\"", @@ -56,6 +57,7 @@ ohos_shared_library("amsDataSystemTestB") { "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn old mode 100644 new mode 100755 index 4e22015ca94f1e9d2e27b37d8e5fb292e347e4ea..84231830d3a5eaf60aa8044569f6359e82cfc540 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn @@ -28,6 +28,7 @@ config("amsDataSystemTestCConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsDataSystemTestC\"", @@ -56,6 +57,7 @@ ohos_shared_library("amsDataSystemTestC") { "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp index c782c465e7ecd7a6109ec889c35bea5f86756ea5..8b10a543671b2240aee2bdde804bb07d89b86eb5 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp @@ -141,17 +141,7 @@ std::vector AmsStDataAbilityDataC1::GetFileTypes(const Uri &uri, co int AmsStDataAbilityDataC1::OpenFile(const Uri &uri, const std::string &mode) { - APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); - - FILE *fd1 = fopen("/system/vendor/test.txt", "r"); - if (fd1 == nullptr) { - APP_LOGI("-------------------------------AmsStDataAbilityDataC1 <<<>>> fdr == nullptr"); - return -1; - } - fd = fileno(fd1); - APP_LOGI("--------------------------------AmsStDataAbilityDataC1 fd: %{public}d", fd); - PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); - return fd; + return 0; } static void GetResult(std::shared_ptr child, std::shared_ptr helper, @@ -227,15 +217,12 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( } } else if (child->GetOperatorName() == OPERATOR_OPENFILE) { APP_LOGI("---------------------OpenFile--------------------"); - int fd = mainAbility->OpenFile(dataAbilityUri, child->GetMessage()); - if (fd < 0) { - return; - } - FILE *file = fdopen(fd, "r"); + FILE *file = fopen("/system/vendor/test.txt", "r"); if (file == nullptr) { return; } - result = std::to_string(fd); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); + char str[5]; if (!feof(file)) fgets(str, 5, file); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/BUILD.gn old mode 100644 new mode 100755 index 90253da90a42f1ebbb957785d40e6534608142ed..5a8500c94a9849c494f79a1c73033700855e799d --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/BUILD.gn @@ -28,6 +28,7 @@ config("amsKitSystemTestconfig") { "//utils/system/safwk/native/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsKitSystemTest\"", @@ -61,6 +62,7 @@ ohos_shared_library("amsKitSystemTest") { "${appexecfwk_path}/services/bundlemgr:libbms", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp index 55901e8cc2788b9b506177c3d40c0b835e09abf2..13294bba9686516da807451d333719e798d2de54 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp @@ -17,6 +17,16 @@ #include "app_log_wrapper.h" #include "ohos/aafwk/base/base_types.h" #include "test_utils.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp old mode 100644 new mode 100755 index 8b3c5b8b199ba72fa9c2e9b83c790c73d64df8de..eca054ab515a8514deeac7708edae12f3931e3d0 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp @@ -18,6 +18,16 @@ #include #include #include "app_log_wrapper.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp old mode 100644 new mode 100755 index ad13d5946ebb7599309d53b65f8528b6e9d8cc26..bd1641853bdd9ef42e0a4b0cfbcf1b930b25fbbd --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp @@ -19,6 +19,17 @@ #include "uri.h" #include "ohos/aafwk/content/operation_builder.h" #include "test_utils.h" +#include "ohos/aafwk/base/array_wrapper.h" +#include "ohos/aafwk/base/bool_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" +#include "ohos/aafwk/base/byte_wrapper.h" +#include "ohos/aafwk/base/short_wrapper.h" +#include "ohos/aafwk/base/int_wrapper.h" +#include "ohos/aafwk/base/long_wrapper.h" +#include "ohos/aafwk/base/float_wrapper.h" +#include "ohos/aafwk/base/double_wrapper.h" +#include "ohos/aafwk/base/string_wrapper.h" +#include "ohos/aafwk/base/zchar_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/BUILD.gn old mode 100644 new mode 100755 index 0a50173b9c063b720194fe045974bc1a538c9280..f68c7c8e560e600361fec65dcc591c69d977f21e --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/BUILD.gn @@ -29,6 +29,7 @@ config("amsKitSystemTestAConfig") { "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsKitSystemTestA\"", @@ -56,6 +57,7 @@ ohos_shared_library("amsKitSystemTestA") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/BUILD.gn old mode 100644 new mode 100755 index 17299a601edaac639ecf1cd4cc4932520146b297..639ca76c8df955b6ec11ec25c660f741087597e6 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/BUILD.gn @@ -29,6 +29,7 @@ config("amsKitSystemTestBConfig") { "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsKitSystemTestB\"", @@ -55,6 +56,7 @@ ohos_shared_library("amsKitSystemTestB") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn old mode 100644 new mode 100755 index aeccfe7ea00bf0df24b185fc59783f2b19f20961..be5a60832a5414c421b41a781a3742cc1bb7749a --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn @@ -29,6 +29,7 @@ config("amsKitSystemTestDataAConfig") { "${common_path}/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsKitDataSystemTestA\"", @@ -60,6 +61,7 @@ ohos_shared_library("amsKitSystemTestDataA") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn old mode 100644 new mode 100755 index 00a21f15d81d6273aacac930493449cb0c07821b..84cfa990b8f864771329875cfcb5cdd1e47eb71a --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn @@ -29,6 +29,7 @@ config("amsKitSystemTestDataBConfig") { "${common_path}/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsKitDataSystemTestB\"", @@ -58,6 +59,7 @@ ohos_shared_library("amsKitSystemTestDataB") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/BUILD.gn index e35cd0f6c19eff1d381adc3998b4a39d615bd0fc..8f89b22f02d038e534cac6eb03b86c269de6e7d4 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsKitSystemTestPageA\"", @@ -54,6 +55,7 @@ ohos_shared_library("amsKitSystemTestPageA") { "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", "${libs_path}/libeventhandler:libeventhandler_target", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/BUILD.gn index cebf6cc9dedc9c6bca2b247eb37725535096a8a7..dd66636ddd2571e5fde840970d7ee87eade46087 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/BUILD.gn @@ -27,6 +27,7 @@ config("amsKitSystemTestServiceconfig") { "${appexecfwk_path}/services/bundlemgr/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "//utils/system/safwk/native/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsKitSystemTestService\"", @@ -59,6 +60,7 @@ ohos_shared_library("amsKitSystemTestService") { "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", "${libs_path}/libeventhandler:libeventhandler_target", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a8fa4ae25bbe77f6167732eb87c8a7581f7510cb --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsMissionStackTestConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${kits_path}/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsMissionStackTest\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsMissionStackTest") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + "${SUBDEMOSYSTEM_DIR}/src/third_ability.cpp", + ] + configs = [ ":amsMissionStackTestConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${kits_path}:appkit_native", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/config.json b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f01c6ef38d0f1181ce245591a91571033f8be7e6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/config.json @@ -0,0 +1,60 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.MissionStack", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.MissionStack.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowflakes", + "label": "Second Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ThirdAbility", + "icon": "$media:snowflakes", + "label": "Third Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..46403d06b73899a34093da2624180529467584b9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/main_ability.h @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 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 AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class FirstEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + void MissionStackCase4(int code); + void MissionStackCase5(int code); + void MissionStackCase6(int code); + void MissionStackCase7(int code); + void MissionStackCase8(int code); + void MissionStackCase9(int code); + void MissionStackCase10(int code); + void MissionStackCase11(int code); + void MissionStackCase12(int code); + void MissionStackCase13(int code); + void MissionStackCase14(int code); + void MissionStackCase15(int code); + void MissionStackCase16(int code); + void MissionStackCase17(int code); + void MissionStackCase18(int code); + + void SaveAbilityStateCase1(int code); + void SaveAbilityStateCase2(int code); + void SaveAbilityStateCase3(int code); + + void RestoreAbilityStateCase1(int code); + void RestoreAbilityStateCase2(int code); + void RestoreAbilityStateCase3(int code); + + MainAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + [this](int code) { MissionStackCase4(code); }, + [this](int code) { MissionStackCase5(code); }, + [this](int code) { MissionStackCase6(code); }, + [this](int code) { MissionStackCase7(code); }, + [this](int code) { MissionStackCase8(code); }, + [this](int code) { MissionStackCase9(code); }, + [this](int code) { MissionStackCase10(code); }, + [this](int code) { MissionStackCase11(code); }, + [this](int code) { MissionStackCase12(code); }, + [this](int code) { MissionStackCase13(code); }, + [this](int code) { MissionStackCase14(code); }, + [this](int code) { MissionStackCase15(code); }, + [this](int code) { MissionStackCase16(code); }, + [this](int code) { MissionStackCase17(code); }, + [this](int code) { MissionStackCase18(code); }, + + }}, + {(int)TestAbilityState::OnSaveAbilityState, + { + [this](int code) { SaveAbilityStateCase1(code); }, + [this](int code) { SaveAbilityStateCase2(code); }, + [this](int code) { SaveAbilityStateCase3(code); }, + }}, + {(int)TestAbilityState::OnRestoreAbilityState, + { + [this](int code) { RestoreAbilityStateCase1(code); }, + [this](int code) { RestoreAbilityStateCase2(code); }, + [this](int code) { RestoreAbilityStateCase3(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + std::shared_ptr subscriber_; +}; +class FirstEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit FirstEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + {"TestAbilityState", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~FirstEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..5c0477bfa3336a2c9b7650617b79a8d8fdc07b06 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/second_ability.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 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 AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + void MissionStackCase4(int code); + void MissionStackCase5(int code); + void MissionStackCase6(int code); + void MissionStackCase7(int code); + void MissionStackCase8(int code); + void MissionStackCase9(int code); + void MissionStackCase10(int code); + void MissionStackCase11(int code); + void MissionStackCase12(int code); + void MissionStackCase13(int code); + void MissionStackCase14(int code); + void MissionStackCase15(int code); + void MissionStackCase16(int code); + void MissionStackCase17(int code); + void MissionStackCase18(int code); + + void SaveAbilityStateCase1(int code); + void SaveAbilityStateCase2(int code); + void SaveAbilityStateCase3(int code); + + void RestoreAbilityStateCase1(int code); + void RestoreAbilityStateCase2(int code); + void RestoreAbilityStateCase3(int code); + + SecondAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + [this](int code) { MissionStackCase4(code); }, + [this](int code) { MissionStackCase5(code); }, + [this](int code) { MissionStackCase6(code); }, + [this](int code) { MissionStackCase7(code); }, + [this](int code) { MissionStackCase8(code); }, + [this](int code) { MissionStackCase9(code); }, + [this](int code) { MissionStackCase10(code); }, + [this](int code) { MissionStackCase11(code); }, + [this](int code) { MissionStackCase12(code); }, + [this](int code) { MissionStackCase13(code); }, + [this](int code) { MissionStackCase14(code); }, + [this](int code) { MissionStackCase15(code); }, + [this](int code) { MissionStackCase16(code); }, + [this](int code) { MissionStackCase17(code); }, + [this](int code) { MissionStackCase18(code); }, + + }}, + {(int)TestAbilityState::OnSaveAbilityState, + { + [this](int code) { SaveAbilityStateCase1(code); }, + [this](int code) { SaveAbilityStateCase2(code); }, + [this](int code) { SaveAbilityStateCase3(code); }, + }}, + {(int)TestAbilityState::OnRestoreAbilityState, + { + [this](int code) { RestoreAbilityStateCase1(code); }, + [this](int code) { RestoreAbilityStateCase2(code); }, + [this](int code) { RestoreAbilityStateCase3(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + std::shared_ptr subscriber_; +}; +class SecondEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + {"TestAbilityState", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + secondAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + secondAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *secondAbility; + std::unordered_map> mapTestFunc_; + ~SecondEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/third_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..a91d270db86ddac23a41ea901f853f176308908c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/include/third_ability.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 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 AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#define AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class ThirdEventSubscriber; +class ThirdAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + void MissionStackCase4(int code); + void MissionStackCase5(int code); + void MissionStackCase6(int code); + void MissionStackCase7(int code); + void MissionStackCase8(int code); + void MissionStackCase9(int code); + void MissionStackCase10(int code); + void MissionStackCase11(int code); + void MissionStackCase12(int code); + void MissionStackCase13(int code); + void MissionStackCase14(int code); + void MissionStackCase15(int code); + void MissionStackCase16(int code); + void MissionStackCase17(int code); + void MissionStackCase18(int code); + + ThirdAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + [this](int code) { MissionStackCase4(code); }, + [this](int code) { MissionStackCase5(code); }, + [this](int code) { MissionStackCase6(code); }, + [this](int code) { MissionStackCase7(code); }, + [this](int code) { MissionStackCase8(code); }, + [this](int code) { MissionStackCase9(code); }, + [this](int code) { MissionStackCase10(code); }, + [this](int code) { MissionStackCase11(code); }, + [this](int code) { MissionStackCase12(code); }, + [this](int code) { MissionStackCase13(code); }, + [this](int code) { MissionStackCase14(code); }, + [this](int code) { MissionStackCase15(code); }, + [this](int code) { MissionStackCase16(code); }, + [this](int code) { MissionStackCase17(code); }, + [this](int code) { MissionStackCase18(code); }, + + }}, + }; + } + + std::unordered_map>> mapCase_; + ~ThirdAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + std::shared_ptr subscriber_; +}; +class ThirdEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit ThirdEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + {"TestAbilityState", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + thirdAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + thirdAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + ThirdAbility *thirdAbility; + std::unordered_map> mapTestFunc_; + ~ThirdEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_ABILITY_APPEND_TEST_A_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9b5b55a86a5f95a2a4275b4b6392cb9dd03e144 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/main_ability.cpp @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2021 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnStop"); +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnActive"); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnForeground"); +} + +void MainAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("MainAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnRestoreAbilityState"); +} +void MainAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("MainAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE, MAIN_ABILITY_CODE, "OnSaveAbilityState"); +} + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_MAIN, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("FirstEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_MAIN.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < 3) { + return; + } + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void MainAbility::MissionStackCase1(int code) +{ + APP_LOGI("MainAbility::MissionStackCase1"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase2(int code) +{ + APP_LOGI("MainAbility::MissionStackCase2"); + bool result = true; + LockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); + TerminateAbility(); +} +void MainAbility::MissionStackCase3(int code) +{ + APP_LOGI("MainAbility::MissionStackCase3"); + bool result = true; + LockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase5(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase6(int code) +{ + APP_LOGI("MainAbility::MissionStackCase6"); + bool result = true; + LockMission(); + std::map params; + Want want = TestUtils::MakeWant("", "ThirdAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase7(int code) +{ + APP_LOGI("MainAbility::MissionStackCase7"); + bool result = true; + LockMission(); + UnlockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase8(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase9(int code) +{ + APP_LOGI("MainAbility::MissionStackCase9"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase10(int code) +{ + APP_LOGI("MainAbility::MissionStackCase10"); + bool result = true; + int missionId = GetMissionId(); + result = missionId >= 0; + //TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(missionId)); +} +void MainAbility::MissionStackCase11(int code) +{ + APP_LOGI("MainAbility::MissionStackCase11"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase12(int code) +{ + APP_LOGI("MainAbility::MissionStackCase12"); + bool result = true; + result = MoveMissionToEnd(true); + if(result){ + APP_LOGI("MainAbility::MissionStackCase12 MoveMissionToEnd(true)true ====> %{public}d",result); + }else{ + APP_LOGI("MainAbility::MissionStackCase12 MoveMissionToEnd(true)false ====> %{public}d",result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase13(int code) +{ + APP_LOGI("MainAbility::MissionStackCase13"); + bool result = true; + result = MoveMissionToEnd(false); + if(result){ + APP_LOGI("MainAbility::MissionStackCase13 MoveMissionToEnd(false)true ====> %{public}d",result); + }else{ + APP_LOGI("MainAbility::MissionStackCase13 MoveMissionToEnd(false)false ====> %{public}d",result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase14(int code) +{ + APP_LOGI("MainAbility::MissionStackCase14"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase15(int code) +{ + APP_LOGI("MainAbility::MissionStackCase15"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase16(int code) +{ + APP_LOGI("MainAbility::MissionStackCase16"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase17(int code) +{ + APP_LOGI("MainAbility::MissionStackCase17"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::MissionStackCase18(int code) +{ + APP_LOGI("MainAbility::MissionStackCase18"); + bool result = true; + LockMission(); + result = MoveMissionToEnd(false); + if(result){ + APP_LOGI("MainAbility::MissionStackCase18 MoveMissionToEnd(false)true ====> %{public}d",result); + }else{ + APP_LOGI("MainAbility::MissionStackCase18 MoveMissionToEnd(false)false ====> %{public}d",result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::SaveAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::SaveAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::SaveAbilityStateCase3(int code) +{ + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} + +void MainAbility::RestoreAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::RestoreAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} +void MainAbility::RestoreAbilityStateCase3(int code) +{ + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_MAIN, code, std::to_string(result)); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d304437fab52ff0ca5abfe962faf673fb1582aa8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/second_ability.cpp @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2021 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnStop"); +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnActive"); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnForeground"); +} + +void SecondAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("SecondAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnRestoreAbilityState"); +} +void SecondAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("SecondAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE, SECOND_ABILITY_CODE, "OnSaveAbilityState"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->secondAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < 3) { + return; + } + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::MissionStackCase1(int code) +{ + bool result = true; + LockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); + TerminateAbility(); +} +void SecondAbility::MissionStackCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase5(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase6(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase7(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase8(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase9(int code) +{ + bool result = true; + LockMission(); + UnlockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); + TerminateAbility(); +} +void SecondAbility::MissionStackCase10(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase11(int code) +{ + bool result = true; + result = MoveMissionToEnd(false); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase12(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase13(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase14(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase14"); + bool result = true; + result = MoveMissionToEnd(true); + if(result){ + APP_LOGI("SecondAbility::MissionStackCase14 MoveMissionToEnd(true)true ====> %{public}d",result); + }else{ + APP_LOGI("SecondAbility::MissionStackCase14 MoveMissionToEnd(true)false ====> %{public}d",result); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase15(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase15"); + bool result = true; + result = MoveMissionToEnd(false); + if(result){ + APP_LOGI("SecondAbility::MissionStackCase15 MoveMissionToEnd(false)true ====> %{public}d",result); + }else{ + APP_LOGI("SecondAbility::MissionStackCase15 MoveMissionToEnd(false)false ====> %{public}d",result); + } + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase16(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase16"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase17(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase17"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::MissionStackCase18(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase18"); + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::SaveAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::SaveAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::SaveAbilityStateCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::RestoreAbilityStateCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::RestoreAbilityStateCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} +void SecondAbility::RestoreAbilityStateCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); + TerminateAbility(); +} + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07ebf00c47128276f0e83d0aa5783fec0a417147 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/test_utils.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg{delim}; + return std::vector{ + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/third_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/third_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91889d1021c9164399146bd63ca811db9ea3612d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/third_ability.cpp @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2021 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 "third_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; + +void ThirdAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("ThirdAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +ThirdAbility::~ThirdAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ThirdAbility::OnStart(const Want &want) +{ + APP_LOGI("ThirdAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnStart"); +} + +void ThirdAbility::OnStop() +{ + APP_LOGI("ThirdAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnStop"); +} + +void ThirdAbility::OnActive() +{ + APP_LOGI("ThirdAbility::OnActive"); + Ability::OnActive(); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnActive"); +} + +void ThirdAbility::OnInactive() +{ + APP_LOGI("ThirdAbility::OnInactive"); + Ability::OnInactive(); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnInactive"); +} + +void ThirdAbility::OnBackground() +{ + APP_LOGI("ThirdAbility::OnBackground"); + Ability::OnBackground(); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnBackground"); +} + +void ThirdAbility::OnForeground(const Want &want) +{ + APP_LOGI("ThirdAbility::OnForeground"); + Ability::OnForeground(want); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnForeground"); +} + +void ThirdAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("ThirdAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnRestoreAbilityState"); +} +void ThirdAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("ThirdAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnSaveAbilityState"); +} + +void ThirdAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_THIRD, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->thirdAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ThirdEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("ThirdEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("ThirdEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("ThirdEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_THIRD.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < 3) { + return; + } + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void ThirdAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("ThirdAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void ThirdAbility::MissionStackCase1(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase2(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase3(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase4(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase5(int code) +{ + bool result = true; + LockMission(); + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStack", params); + AbilityContext::StartAbility(want, 1); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase6(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase7(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase8(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase9(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase10(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase11(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase12(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase13(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase14(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase15(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase16(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase17(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +void ThirdAbility::MissionStackCase18(int code) +{ + bool result = true; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +} +REGISTER_AA(ThirdAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5d3f150d5bc44763c1ffed78897562f062b250e9 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("amsMissionStackTestSubsidiaryConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${kits_path}/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "${SUBST_TOOLS_DIR}/include", + ] + defines = [ + "APP_LOG_TAG = \"amsMissionStackTestSubsidiary\"", + "LOG_DOMAIN = 0xD002200", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} +ohos_shared_library("amsMissionStackTestSubsidiary") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/main_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/second_ability.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_utils.cpp", + "${SUBDEMOSYSTEM_DIR}/src/third_ability.cpp", + ] + configs = [ ":amsMissionStackTestSubsidiaryConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${kits_path}:appkit_native", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "amssystemtestability" +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/config.json b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8908968c323ae84a4d1bfbaf3e2fc63ab018c4d6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/config.json @@ -0,0 +1,60 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.MissionStackSubsidiary", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.MissionStackSubsidiary.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "MainAbility", + "icon": "$media:snowball", + "label": "MainAbility label", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + ] + }, + { + "name": "SecondAbility", + "icon": "$media:snowball", + "label": "SecondAbility label", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ThirdAbility", + "icon": "$media:snowball", + "label": "ThirdAbility label", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/main_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..789530e3d5b7b51c90f4fd1284804438973373ee --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/main_ability.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 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 AMS_FWK_MISSIONSTACK_TEST_MAIN_ABILITY_H +#define AMS_FWK_MISSIONSTACK_TEST_MAIN_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class MainAbilityEventSubscriber; +class MainAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void MissionStackCase1(int code); + void MissionStackCase2(int code); + void MissionStackCase3(int code); + + MainAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + [this](int code) { MissionStackCase3(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~MainAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + std::string callbackSeq; + std::string callbackUpdated; +}; +class MainAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit MainAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + mainAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + mainAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + MainAbility *mainAbility; + std::unordered_map> mapTestFunc_; + ~MainAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_FWK_MISSIONSTACK_TEST_MAIN_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/second_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..f425db4c8b65882acddf34e58b985ae0cde5aec8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/second_ability.h @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 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 AMS_FWK_MISSIONSTACK_TEST_SECOND_ABILITY_H +#define AMS_FWK_MISSIONSTACK_TEST_SECOND_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class SecondAbilityEventSubscriber; +class SecondAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + void MissionStackCase1(int code); + void MissionStackCase2(int code); + + SecondAbility() + { + mapCase_ = { + {(int)MissionStackApi::LockMission, + { + [this](int code) { MissionStackCase1(code); }, + [this](int code) { MissionStackCase2(code); }, + }}, + }; + } + + std::unordered_map>> mapCase_; + ~SecondAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnRestoreAbilityState(const PacMap &inState) override; + virtual void OnSaveAbilityState(PacMap &outState) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class SecondAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit SecondAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + {"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + secondAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + secondAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + SecondAbility *secondAbility; + std::unordered_map> mapTestFunc_; + ~SecondAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_FWK_MISSIONSTACK_TEST_SECOND_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..64b40f888ec52c9ea73da85d972d20bc734ad447 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/test_utils.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 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 TEST_UTILS_H +#define TEST_UTILS_H +#include "ability_info.h" +#include "ability_lifecycle.h" +#include "application_info.h" +#include "process_info.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +const int OnStateChangedEventWant = LifeCycle::Event::UNDEFINED; +const int OnStateChangedEvent = (int)LifeCycle::Event::UNDEFINED + 1; +const int requestCodeForTerminate = 10; +const int requestCodeForResult = 20; + +class TestUtils { +public: + TestUtils() = default; + virtual ~TestUtils() = default; + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, + std::map params); + static std::vector split(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // TEST_UTILS_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/third_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..09bb7c7dfa13dcb1e1efc17f251c7ae93000ed89 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/third_ability.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2021 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 AMS_FWK_MISSIONSTACK_TEST_THIRD_ABILITY_H +#define AMS_FWK_MISSIONSTACK_TEST_THIRD_ABILITY_H +#include "ability.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "ability_append_test_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +class ThirdAbilityEventSubscriber; +class ThirdAbility : public Ability { +public: + void SubscribeEvent(); + void TestAbility(int apiIndex, int caseIndex, int code); + + // void MissionStackCase1(int code); + // void MissionStackCase2(int code); + + ThirdAbility() + { + mapCase_ = { + // {(int)MissionStackApi::LockMission, + // { + // [this](int code) { MissionStackCase1(code); }, + // [this](int code) { MissionStackCase2(code); }, + // }}, + }; + } + + std::unordered_map>> mapCase_; + ~ThirdAbility(); + +protected: + void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, + std::shared_ptr &handler, const sptr &token) override; + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnForeground(const Want &want) override; + virtual void OnConfigurationUpdated(const Configuration &configuration) override; + + std::shared_ptr subscriber_; + + std::string callbackSeq; + std::string callbackUpdated; +}; +class ThirdAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + explicit ThirdAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + { + mapTestFunc_ = { + //{"MissionStack", [this](int apiIndex, int caseIndex, int code) { TestAbility(apiIndex, caseIndex, code); }}, + }; + thirdAbility = nullptr; + } + + void TestAbility(int apiIndex, int caseIndex, int code) + { + thirdAbility->TestAbility(apiIndex, caseIndex, code); + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + + ThirdAbility *thirdAbility; + std::unordered_map> mapTestFunc_; + ~ThirdAbilityEventSubscriber() = default; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // AMS_FWK_MISSIONSTACK_TEST_THIRD_ABILITY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/main_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2e3383400c036d19bb12bc6b2826db0d0928e2f0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/main_ability.cpp @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2021 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 "main_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void MainAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("MainAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +MainAbility::~MainAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void MainAbility::OnStart(const Want &want) +{ + APP_LOGI("MainAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnStart"); +} + +void MainAbility::OnStop() +{ + APP_LOGI("MainAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + //callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + callbackSeq = "OnStop"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnActive() +{ + APP_LOGI("MainAbility::OnActive====<"); + Ability::OnActive(); + //callbackSeq += "OnActive"; //OnStartOnActive + callbackSeq = "OnActive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void MainAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("MainAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, callbackUpdated); +} + +void MainAbility::OnInactive() +{ + APP_LOGI("MainAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnInactive"); +} + +void MainAbility::OnBackground() +{ + APP_LOGI("MainAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnBackground"); +} + +void MainAbility::OnForeground(const Want &want) +{ + APP_LOGI("MainAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, MAIN_ABILITY_CODE_SUBSIDIARY, "OnForeground"); +} + + +void MainAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_MAIN_SUBSIDIARY, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void MainAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("MainAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_MAIN_SUBSIDIARY.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < 3) { + return; + } + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("MainAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + + +void MainAbility::MissionStackCase1(int code) +{ + APP_LOGI("MainAbility::MissionStackCase1"); + bool result = true; + std::map params; + Want want = TestUtils::MakeWant("", "SecondAbility", "com.ohos.amsst.MissionStackSubsidiary", params); + AbilityContext::StartAbility(want, 1); + + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_SUBSIDIARY, code, std::to_string(result)); +} + +void MainAbility::MissionStackCase2(int code) +{ + APP_LOGI("MainAbility::MissionStackCase2"); + bool result = true; + result = MoveMissionToEnd(true); + if(result){ + APP_LOGI("MainAbility::MissionStackCase2 MoveMissionToEnd(true)true ====> %{public}d",result); + }else{ + APP_LOGI("MainAbility::MissionStackCase2 MoveMissionToEnd(true)false ====> %{public}d",result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_SUBSIDIARY, code, std::to_string(result)); +} +void MainAbility::MissionStackCase3(int code) +{ + APP_LOGI("MainAbility::MissionStackCase3"); + bool result = true; + result = MoveMissionToEnd(false); + if(result){ + APP_LOGI("MainAbility::MissionStackCase3 MoveMissionToEnd(false)true ====> %{public}d",result); + }else{ + APP_LOGI("MainAbility::MissionStackCase3 MoveMissionToEnd(false)false ====> %{public}d",result); + } + TestUtils::PublishEvent(g_EVENT_RESP_MAIN_SUBSIDIARY, code, std::to_string(result)); +} + +REGISTER_AA(MainAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/second_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f09c50648d48a0a5f105129b4e639de634470c05 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/second_ability.cpp @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2021 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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void SecondAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("SecondAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +SecondAbility::~SecondAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void SecondAbility::OnStart(const Want &want) +{ + APP_LOGI("SecondAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnStart"); +} + +void SecondAbility::OnStop() +{ + APP_LOGI("SecondAbility::OnStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + //callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + callbackSeq = "OnStop"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnActive() +{ + APP_LOGI("SecondAbility::OnActive====<"); + Ability::OnActive(); + //callbackSeq += "OnActive"; //OnStartOnActive + callbackSeq = "OnActive"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, callbackSeq); + callbackSeq = ""; +} + +void SecondAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("SecondAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, callbackUpdated); +} + +void SecondAbility::OnInactive() +{ + APP_LOGI("SecondAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnInactive"); +} + +void SecondAbility::OnBackground() +{ + APP_LOGI("SecondAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnBackground"); +} + +void SecondAbility::OnForeground(const Want &want) +{ + APP_LOGI("SecondAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnForeground"); +} + +void SecondAbility::OnRestoreAbilityState(const PacMap &inState) +{ + APP_LOGI("SecondAbility::OnRestoreAbilityState"); + Ability::OnRestoreAbilityState(inState); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnRestoreAbilityState"); +} +void SecondAbility::OnSaveAbilityState(PacMap &outState) +{ + APP_LOGI("SecondAbility::OnSaveAbilityState"); + Ability::OnSaveAbilityState(outState); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, SECOND_ABILITY_CODE_SUBSIDIARY, "OnSaveAbilityState"); +} + +void SecondAbility::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_REQU_SECOND_SUBSIDIARY, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->secondAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void SecondAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("SecondAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { + auto target = data.GetData(); + auto caseInfo = TestUtils::split(target, "_"); + if (caseInfo.size() < 3) { + return; + } + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } +} + +void SecondAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("SecondAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +void SecondAbility::MissionStackCase1(int code) +{ + APP_LOGI("SecondAbility::MissionStackCase1====<"); + bool result = true; + result = true; + + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +void SecondAbility::MissionStackCase2(int code) +{ + bool result = true; + result = true; + // LockMission(); + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); + //TerminateAbility(); +} +// void SecondAbility::MissionStackCase3(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +// TerminateAbility(); +// } + +REGISTER_AA(SecondAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07ebf00c47128276f0e83d0aa5783fec0a417147 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/test_utils.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 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 "test_utils.h" +#include +#include +#include +#include +#include "common_event_data.h" +#include "common_event_manager.h" +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +bool TestUtils::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + +Want TestUtils::MakeWant( + std::string deviceId, std::string abilityName, std::string bundleName, std::map params) +{ + ElementName element(deviceId, bundleName, abilityName); + Want want; + want.SetElement(element); + for (const auto ¶m : params) { + want.SetParam(param.first, param.second); + } + return want; +} + +std::vector TestUtils::split(const std::string &in, const std::string &delim) +{ + std::regex reg{delim}; + return std::vector{ + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/third_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/third_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0a1661082bd458631f038087aff1473abfe65c3 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/third_ability.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021 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 "third_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; + +void ThirdAbility::Init(const std::shared_ptr &abilityInfo, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + APP_LOGI("ThirdAbility::Init"); + Ability::Init(abilityInfo, application, handler, token); +} + +ThirdAbility::~ThirdAbility() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void ThirdAbility::OnStart(const Want &want) +{ + APP_LOGI("ThirdAbility::OnStart"); + SubscribeEvent(); + Ability::OnStart(want); + callbackSeq += "OnStart"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnStart"); +} + +void ThirdAbility::OnStop() +{ + APP_LOGI("ThirdAbility::OnStop"); + Ability::OnStop(); + callbackSeq += "OnStop"; //OnInactiveOnBackgroundOnStop + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void ThirdAbility::OnActive() +{ + APP_LOGI("ThirdAbility::OnActive====<"); + Ability::OnActive(); + callbackSeq += "OnActive"; //OnStartOnActive + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackSeq); + callbackSeq = ""; +} + +void ThirdAbility::OnConfigurationUpdated(const Configuration &configuration) +{ + APP_LOGI("ThirdAbility::OnConfigurationUpdated====<"); + Ability::OnConfigurationUpdated(configuration); + callbackUpdated += "Updated"; //UpdatedUpdated + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, callbackUpdated); +} + +void ThirdAbility::OnInactive() +{ + APP_LOGI("ThirdAbility::OnInactive"); + Ability::OnInactive(); + callbackSeq += "OnInactive"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnInactive"); +} + +void ThirdAbility::OnBackground() +{ + APP_LOGI("ThirdAbility::OnBackground"); + Ability::OnBackground(); + callbackSeq += "OnBackground"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnBackground"); +} + +void ThirdAbility::OnForeground(const Want &want) +{ + APP_LOGI("ThirdAbility::OnForeground"); + Ability::OnForeground(want); + callbackSeq += "OnForeground"; + TestUtils::PublishEvent(g_EVENT_RESP_THIRD_LIFECYCLE, THIRD_ABILITY_CODE, "OnForeground"); +} + +void ThirdAbility::SubscribeEvent() +{ + std::vector eventList = { + //g_EVENT_REQU_THIRD, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->thirdAbility = this; + CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void ThirdAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("ThirdAbilityEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + // if (std::strcmp(eventName.c_str(), g_EVENT_REQU_THIRD.c_str()) == 0) { + // auto target = data.GetData(); + // auto caseInfo = TestUtils::split(target, "_"); + // if (caseInfo.size() < 3) { + // return; + // } + // if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + // mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + // } else { + // APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + // } + // } +} + +void ThirdAbility::TestAbility(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("ThirdAbility::TestAbility"); + if (mapCase_.find(apiIndex) != mapCase_.end()) { + if (caseIndex < (int)mapCase_[apiIndex].size()) { + mapCase_[apiIndex][caseIndex](code); + } + } +} + +// void ThirdAbility::MissionStackCase1(int code) +// { +// APP_LOGI("ThirdAbility::MissionStackCase1====<"); +// bool result = true; +// result = true; +// const std::shared_ptr dcf = std::make_shared("orientation"); +// unsigned int flag = dcf->Differ(dcf); +// APP_LOGI("ThirdAbility::MissionStackCase1==flag====>%{public}d",flag); +// Configuration configuration; +// std::string configName = configuration.GetName(); +// APP_LOGI("ThirdAbility::MissionStackCase1==configName====>%{public}s",configName.c_str()); +// //configuration.getContext().setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE); +// //configuration.UpdateConfiguration(dcf); + +// //TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +// } + +// void ThirdAbility::MissionStackCase2(int code) +// { +// bool result = true; +// result = true; +// // LockMission(); +// // TestUtils::PublishEvent(g_EVENT_RESP_THIRD, code, std::to_string(result)); +// TerminateAbility(); +// } + + +REGISTER_AA(ThirdAbility) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/BUILD.gn old mode 100644 new mode 100755 index 15c1495a73595a91ad42f6e69c77f4f50d5fc1bb..156c6a2bff361afb302daf234eb86ce24c80d690 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestAConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestA\"", @@ -51,6 +52,7 @@ ohos_shared_library("amsSystemTestA") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya1.cpp index 8c0312b44ba54dc10b57079ca927e2430c74b0d2..1c7a0d712da3745eb548ee092d0cefa755d3a876 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityA1::OnStart(const Want &want) void AmsStAbilityA1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityA1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityA1::OnNewWant(const Want &want) void AmsStAbilityA1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityA1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya2.cpp index 0c4e38118c0eb22375af85ca2c671b096a6c5eed..92f5ee7d67a389e13bee447b9f695edfec3f12d5 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestA/src/amsstabilitya2.cpp @@ -30,8 +30,6 @@ void AmsStAbilityA2::OnStart(const Want &want) void AmsStAbilityA2::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityA2::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityA2::OnForeground(const Want &want) void AmsStAbilityA2::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityA2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/BUILD.gn old mode 100644 new mode 100755 index a04c7f21a789b7ab7f01e27cbd906b43bfe44840..27d86538623f8e2aaee5aaab3b68193099d8c00e --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestBConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestB\"", @@ -46,6 +47,7 @@ ohos_shared_library("amsSystemTestB") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/src/amsstabilityb1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/src/amsstabilityb1.cpp index 2baf721d33df57289e356da526909f213a4d0ebd..772751a38ea2095b304a3ee6cf859422ff594ea8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/src/amsstabilityb1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestB/src/amsstabilityb1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityB1::OnStart(const Want &want) void AmsStAbilityB1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityB1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityB1::OnNewWant(const Want &want) void AmsStAbilityB1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityB1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/BUILD.gn old mode 100644 new mode 100755 index 74f3c45135c0b7ae88f752b9ea4bcfa185146bd1..c81204b8bdcb62b6b16999be371aaadcd82e14dc --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestC\"", @@ -48,6 +49,7 @@ ohos_shared_library("amsSystemTestC") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc1.cpp index 3ee14eb0348c15b402be3961a7a9837a90df8a0d..cd43e18e9d43c87ca012893476c1a93cf2e6a8e5 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityC1::OnStart(const Want &want) void AmsStAbilityC1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityC1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityC1::OnForeground(const Want &want) void AmsStAbilityC1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityC1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc2.cpp index 05e5925bb77bf043c10e2a83cf02018187b6e94f..71f932129b4291b0e4ae25fbe6e9b2b5291e4c1c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc2.cpp @@ -30,8 +30,6 @@ void AmsStAbilityC2::OnStart(const Want &want) void AmsStAbilityC2::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityC2::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityC2::OnForeground(const Want &want) void AmsStAbilityC2::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityC2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc3.cpp index 90d263f1d58344a681e5c9c4988516f588d9a5b0..8fd4ca9f158feaf8966519b19eb48930ac63603b 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestC/src/amsstabilityc3.cpp @@ -30,8 +30,6 @@ void AmsStAbilityC3::OnStart(const Want &want) void AmsStAbilityC3::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityC3::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityC3::OnForeground(const Want &want) void AmsStAbilityC3::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityC3::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/BUILD.gn old mode 100644 new mode 100755 index e5af356eb02b5aaa342b183853299a73d8604e91..98707b8276696af9ad56653e8c18f1078732b23c --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestDConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestD\"", @@ -47,6 +48,7 @@ ohos_shared_library("amsSystemTestD") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd1.cpp index 1a4ee0f5bb718fb6cd04d1fbff15342ace1428a9..eaf945217286deb1d812524c1f1955c5748e206d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityD1::OnStart(const Want &want) void AmsStAbilityD1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityD1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityD1::OnForeground(const Want &want) void AmsStAbilityD1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityD1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd2.cpp index f25593bd85b9cb4f718072af54b7d7abe4299d8f..e824e91a27b74409ee5fbd9953891efb88695d62 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestD/src/amsstabilityd2.cpp @@ -30,8 +30,6 @@ void AmsStAbilityD2::OnStart(const Want &want) void AmsStAbilityD2::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityD2::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityD2::OnForeground(const Want &want) void AmsStAbilityD2::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityD2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/BUILD.gn index 9c933fd95ebcbfef68ce96ab05dcc202b9d04e15..429a39e5d09200383c4812aec0528da1ca61f28b 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/BUILD.gn @@ -28,6 +28,7 @@ config("amsSystemTestCConfig") { "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestDFX\"", @@ -50,6 +51,7 @@ ohos_shared_library("amsSystemTestDFX") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/config.json b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/config.json index 477d5ad10e06b9ad1730da6c4f9193f6073f6ce6..33ba5b26bf9b27fc1de02f60205184fba987c769 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/config.json +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/config.json @@ -28,18 +28,18 @@ "moduleType": "entry" }, "abilities": [{ - "name": "AmsStAbilityDFXA1", + "name": "AmsDfxStServiceAbilityA1", "icon": "$media:snowball", - "label": "AmsStAbilityDFXA1 Ability", + "label": "AmsDfxStServiceAbilityA1 Ability", "launchType": "standard", "orientation": "unspecified", "type": "service", "visible": true }, { - "name": "AmsStAbilityDFXA2", + "name": "AmsDfxStServiceAbilityA2", "icon": "$media:snowball", - "label": "AmsStAbilityDFXA2 Ability", + "label": "AmsDfxStServiceAbilityA1 Ability", "launchType": "standard", "orientation": "unspecified", "type": "service", diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a1.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a1.h index f4b287f15d56ce32c36075785ebade371c02208a..4ccaa06123199b5941a6720b99f0585c46a061b5 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a1.h +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a1.h @@ -28,9 +28,9 @@ namespace OHOS { namespace AppExecFwk { -class AmsStAbilityDFXA1 : public Ability { +class AmsDfxStServiceAbilityA1 : public Ability { public: - ~AmsStAbilityDFXA1(); + ~AmsDfxStServiceAbilityA1(); protected: virtual void OnStart(const Want &want) override; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a2.h b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a2.h index bfb0f28970ea54c1e6d1072d111f2fee14aff07c..7ff31a30f55cadd65b6a5eecdea3674ae2bf1968 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a2.h +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/include/ams_dfx_st_service_ability_a2.h @@ -28,9 +28,9 @@ namespace OHOS { namespace AppExecFwk { -class AmsStAbilityDFXA2 : public Ability { +class AmsDfxStServiceAbilityA2 : public Ability { public: - ~AmsStAbilityDFXA2(); + ~AmsDfxStServiceAbilityA2(); protected: virtual void OnStart(const Want &want) override; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a1.cpp index 5209db83caa3c1f4604d0d14053ac0073fb51efc..9439d31855c4a4eb61f2c0346b58d46972f9ca29 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a1.cpp @@ -22,39 +22,39 @@ using namespace OHOS::EventFwk; namespace OHOS { namespace AppExecFwk { -AmsStAbilityDFXA1::~AmsStAbilityDFXA1() +AmsDfxStServiceAbilityA1::~AmsDfxStServiceAbilityA1() {} -void AmsStAbilityDFXA1::OnStart(const Want &want) +void AmsDfxStServiceAbilityA1::OnStart(const Want &want) { - APP_LOGI("AmsStAbilityDFXA1::OnStart"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnStart"); pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); Ability::OnStart(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); } -void AmsStAbilityDFXA1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +void AmsDfxStServiceAbilityA1::OnCommand(const AAFwk::Want &want, bool restart, int startId) { - APP_LOGI("AmsStAbilityDFXA1::OnCommand"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnCommand"); Ability::OnCommand(want, restart, startId); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); } -void AmsStAbilityDFXA1::OnNewWant(const Want &want) +void AmsDfxStServiceAbilityA1::OnNewWant(const Want &want) { - APP_LOGI("AmsStAbilityDFXA1::OnNewWant"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); } -void AmsStAbilityDFXA1::OnStop() +void AmsDfxStServiceAbilityA1::OnStop() { - APP_LOGI("AmsStAbilityDFXA1::OnStop"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnStop"); Ability::OnStop(); pageAbilityEvent.UnsubscribeEvent(); @@ -62,36 +62,36 @@ void AmsStAbilityDFXA1::OnStop() pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); } -void AmsStAbilityDFXA1::OnActive() +void AmsDfxStServiceAbilityA1::OnActive() { - APP_LOGI("AmsStAbilityDFXA1::OnActive"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnActive"); Ability::OnActive(); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); } -void AmsStAbilityDFXA1::OnInactive() +void AmsDfxStServiceAbilityA1::OnInactive() { - APP_LOGI("AmsStAbilityDFXA1::OnInactive"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnInactive"); Ability::OnInactive(); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); } -void AmsStAbilityDFXA1::OnBackground() +void AmsDfxStServiceAbilityA1::OnBackground() { - APP_LOGI("AmsStAbilityDFXA1::OnBackground"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnBackground"); Ability::OnBackground(); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); } -sptr AmsStAbilityDFXA1::OnConnect(const Want &want) +sptr AmsDfxStServiceAbilityA1::OnConnect(const Want &want) { - APP_LOGI("AmsStAbilityDFXA1::OnConnect"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnConnect"); sptr ret = Ability::OnConnect(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; @@ -100,15 +100,15 @@ sptr AmsStAbilityDFXA1::OnConnect(const Want &want) return ret; } -void AmsStAbilityDFXA1::OnDisconnect(const Want &want) +void AmsDfxStServiceAbilityA1::OnDisconnect(const Want &want) { - APP_LOGI("AmsStAbilityDFXA1::OnDisconnect"); + APP_LOGI("AmsDfxStServiceAbilityA1::OnDisconnect"); Ability::OnDisconnect(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnDisconnectCount(), eventData); } -REGISTER_AA(AmsStAbilityDFXA1); +REGISTER_AA(AmsDfxStServiceAbilityA1); } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a2.cpp index 6d3b8b0bb3624c180d24dd7ae3cf9ea64174f8a5..2caa34eb6f8299c938e488ddd3825e70b0ffa4db 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestDFX/src/ams_dfx_st_service_ability_a2.cpp @@ -22,39 +22,39 @@ using namespace OHOS::EventFwk; namespace OHOS { namespace AppExecFwk { -AmsStAbilityDFXA2::~AmsStAbilityDFXA2() +AmsDfxStServiceAbilityA2::~AmsDfxStServiceAbilityA2() {} -void AmsStAbilityDFXA2::OnStart(const Want &want) +void AmsDfxStServiceAbilityA2::OnStart(const Want &want) { - APP_LOGI("AmsStAbilityDFXA2::OnStart"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnStart"); pageAbilityEvent.SubscribeEvent(STEventName::g_eventList, shared_from_this()); Ability::OnStart(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnStart; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStartCount(), eventData); } -void AmsStAbilityDFXA2::OnCommand(const AAFwk::Want &want, bool restart, int startId) +void AmsDfxStServiceAbilityA2::OnCommand(const AAFwk::Want &want, bool restart, int startId) { - APP_LOGI("AmsStAbilityDFXA2::OnCommand"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnCommand"); Ability::OnCommand(want, restart, startId); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnCommand; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnCommandCount(), eventData); } -void AmsStAbilityDFXA2::OnNewWant(const Want &want) +void AmsDfxStServiceAbilityA2::OnNewWant(const Want &want) { - APP_LOGI("AmsStAbilityDFXA2::OnNewWant"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnNewWantCount(), eventData); } -void AmsStAbilityDFXA2::OnStop() +void AmsDfxStServiceAbilityA2::OnStop() { - APP_LOGI("AmsStAbilityDFXA2::OnStop"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnStop"); Ability::OnStop(); pageAbilityEvent.UnsubscribeEvent(); @@ -62,36 +62,36 @@ void AmsStAbilityDFXA2::OnStop() pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnStopCount(), eventData); } -void AmsStAbilityDFXA2::OnActive() +void AmsDfxStServiceAbilityA2::OnActive() { - APP_LOGI("AmsStAbilityDFXA2::OnActive"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnActive"); Ability::OnActive(); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnActive; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnActiveCount(), eventData); } -void AmsStAbilityDFXA2::OnInactive() +void AmsDfxStServiceAbilityA2::OnInactive() { - APP_LOGI("AmsStAbilityDFXA2::OnInactive"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnInactive"); Ability::OnInactive(); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnInactive; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnInactiveCount(), eventData); } -void AmsStAbilityDFXA2::OnBackground() +void AmsDfxStServiceAbilityA2::OnBackground() { - APP_LOGI("AmsStAbilityDFXA2::OnBackground"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnBackground"); Ability::OnBackground(); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); } -sptr AmsStAbilityDFXA2::OnConnect(const Want &want) +sptr AmsDfxStServiceAbilityA2::OnConnect(const Want &want) { - APP_LOGI("AmsStAbilityDFXA2::OnConnect"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnConnect"); sptr ret = Ability::OnConnect(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnConnect; @@ -99,9 +99,9 @@ sptr AmsStAbilityDFXA2::OnConnect(const Want &want) return ret; } -void AmsStAbilityDFXA2::OnDisconnect(const Want &want) +void AmsDfxStServiceAbilityA2::OnDisconnect(const Want &want) { - APP_LOGI("AmsStAbilityDFXA2::OnDisconnect"); + APP_LOGI("AmsDfxStServiceAbilityA2::OnDisconnect"); Ability::OnDisconnect(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnDisconnect; @@ -109,6 +109,6 @@ void AmsStAbilityDFXA2::OnDisconnect(const Want &want) std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::DISCONNECT_TIMEOUT)); } -REGISTER_AA(AmsStAbilityDFXA2); +REGISTER_AA(AmsDfxStServiceAbilityA2); } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/BUILD.gn old mode 100644 new mode 100755 index 41780838261f309eaff7258ddea9c0cbdfadfe3c..00aa9dbd21d979be14f817dc509c5892a433b6bb --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestEConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestE\"", @@ -46,6 +47,7 @@ ohos_shared_library("amsSystemTestE") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/src/amsstabilitye1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/src/amsstabilitye1.cpp index d3c117609a260450738f31c39f01197c7a2fd7ed..777bfcd11070b0cfdbe7c98d6695233a8faaeb43 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/src/amsstabilitye1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestE/src/amsstabilitye1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityE1::OnStart(const Want &want) void AmsStAbilityE1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityE1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityE1::OnForeground(const Want &want) void AmsStAbilityE1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityE1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/BUILD.gn old mode 100644 new mode 100755 index b78da6e138076024eb908e611e4ee64c24b88e27..bc33e323316ae085dc17f58df54bd62ed3177d26 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorK/BUILD.gn @@ -24,6 +24,7 @@ config("amsSystemTestErrorKConfig") { "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestErrorK\"", @@ -41,6 +42,7 @@ ohos_shared_library("amsSystemTestErrorK") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/BUILD.gn old mode 100644 new mode 100755 index b70af14f9393f65be2748f0c4771398c1d28bf72..5e83dafe190658d7e5d87b1f53f990f545fc2d23 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestErrorL/BUILD.gn @@ -24,6 +24,7 @@ config("amsSystemTestErrorLConfig") { "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestErrorL\"", @@ -41,6 +42,7 @@ ohos_shared_library("amsSystemTestErrorL") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/BUILD.gn old mode 100644 new mode 100755 index 5e524aaade53f854e36a74e59dd0b54a159a2657..dc4136cf9b46fac39c7a5e7460f07d0ffe7c94c4 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestFConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestF\"", @@ -48,6 +49,7 @@ ohos_shared_library("amsSystemTestF") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf1.cpp index 0e6a3b83411657959b1dfa17576244b3a1c4f462..8c3122a77089837e9fa192ae1870d21aa3cb1b91 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityF1::OnStart(const Want &want) void AmsStAbilityF1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityF1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityF1::OnForeground(const Want &want) void AmsStAbilityF1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityF1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf2.cpp index f04092f24bcf75a1345a56a8d4a46fd039da647c..d9e448a0bea91f41dede80cb8fa5fe057e2524ad 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf2.cpp @@ -30,8 +30,6 @@ void AmsStAbilityF2::OnStart(const Want &want) void AmsStAbilityF2::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityF2::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityF2::OnForeground(const Want &want) void AmsStAbilityF2::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityF2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf3.cpp index aefb1e404f7f1577154d80543b4382133da664ab..710c33c97b079c2f5fa4ab62a4e32e771a24ee56 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestF/src/amsstabilityf3.cpp @@ -30,8 +30,6 @@ void AmsStAbilityF3::OnStart(const Want &want) void AmsStAbilityF3::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityF3::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; @@ -40,8 +38,6 @@ void AmsStAbilityF3::OnForeground(const Want &want) void AmsStAbilityF3::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityF2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/BUILD.gn old mode 100644 new mode 100755 index 7774c08c8c368158a597e98f36d3ff4c77c9e258..e9947d0e397585dcc61fb81040f72ad19365928b --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestGConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestG\"", @@ -47,6 +48,7 @@ ohos_shared_library("amsSystemTestG") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg1.cpp index ae4cfab6e65f106c8dc8fc35b97ab9ddde063792..acc830c02fa98ae82f4c0fbdfc028affc0a5d219 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityG1::OnStart(const Want &want) void AmsStAbilityG1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityG1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityG1::OnNewWant(const Want &want) void AmsStAbilityG1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityG1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg2.cpp index d2c2e3fa85edd05ee53794aa35001effe2555ff6..a857a1fe771c20afb6382d70e28c1f184a90a544 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestG/src/amsstabilityg2.cpp @@ -30,8 +30,6 @@ void AmsStAbilityG2::OnStart(const Want &want) void AmsStAbilityG2::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityG2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityG2::OnNewWant(const Want &want) void AmsStAbilityG2::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityG2::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/BUILD.gn old mode 100644 new mode 100755 index 23c0b47df1a3f50d9274ee9d55a78b1281098d42..ccb954150ea87af167f2a74c7466d618507a4aed --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestHConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestH\"", @@ -46,6 +47,7 @@ ohos_shared_library("amsSystemTestH") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/src/amsstabilityh1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/src/amsstabilityh1.cpp index 985fda227f394613da8236579a775cf85668f53d..46c9a8c21b3fc9bab67e1409324c87cc3eb088ec 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/src/amsstabilityh1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestH/src/amsstabilityh1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityH1::OnStart(const Want &want) void AmsStAbilityH1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityH1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityH1::OnNewWant(const Want &want) void AmsStAbilityH1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityH1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/BUILD.gn old mode 100644 new mode 100755 index 93d83c87e135cde2602a1c9881a9cbb8f1acddc9..1731b522d26c0792f6ea5b564be037dae186c57d --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestIConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestI\"", @@ -49,6 +50,7 @@ ohos_shared_library("amsSystemTestI") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi1.cpp index d5548548e132fbbab292c5eaf0f3a106f325319d..796dee708c6e12e3547f2554a450dcc08cffb0f5 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi1.cpp @@ -30,8 +30,6 @@ void AmsStAbilityI1::OnStart(const Want &want) void AmsStAbilityI1::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI1::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityI1::OnNewWant(const Want &want) void AmsStAbilityI1::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi2.cpp index e90ee9f80a88f8434b5d62b3d6c5bcf70d23ffe7..4f2c8bc934a6e3c41f58ea1541f68e7fd9ce1ae6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi2.cpp @@ -30,8 +30,6 @@ void AmsStAbilityI2::OnStart(const Want &want) void AmsStAbilityI2::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI2::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityI2::OnNewWant(const Want &want) void AmsStAbilityI2::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi3.cpp index f9c1ac4de35696bbf53d93f4087b502937151600..b0758a5caedcd95c3158998eb4b04e27e68fcc7b 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi3.cpp @@ -30,8 +30,6 @@ void AmsStAbilityI3::OnStart(const Want &want) void AmsStAbilityI3::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI3::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityI3::OnNewWant(const Want &want) void AmsStAbilityI3::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi4.cpp index 6bd9aab96a705af1526b6ae48e49c42b3b8626b5..566f97e306ea8c07b3f085c7fee8ac4f3d578e56 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi4.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestI/src/amsstabilityi4.cpp @@ -30,8 +30,6 @@ void AmsStAbilityI4::OnStart(const Want &want) void AmsStAbilityI4::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI4::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityI4::OnNewWant(const Want &want) void AmsStAbilityI4::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityI1::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/BUILD.gn old mode 100644 new mode 100755 index 7169e15dc40fa8854efa1c5d9e85c334d144f711..9e0e2be132714c70aa1a2074a94ed5f43f4d1a52 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestMConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestM\"", @@ -46,6 +47,7 @@ ohos_shared_library("amsSystemTestM") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/src/amsstabilitym1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/src/amsstabilitym1.cpp index 4d0baba84c59c46377c1728bd3d7b84b86905fb5..55728cd7ef14052c051c5f93aa90b742c33ceadb 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/src/amsstabilitym1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestM/src/amsstabilitym1.cpp @@ -145,8 +145,8 @@ void AmsStAbilityM1::SendPath(const std::string &callBackPath) std::string abilityStatus = pageAbilityEvent.GetAbilityStatus(std::to_string(Ability::GetState())); std::string callBackPathEventData = Ability::GetAbilityName() + callBack; std::string abilityStatusEventData = Ability::GetAbilityName() + abilityStatus; - pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::eventCode, callBackPathEventData); - pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::eventCode, abilityStatusEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, callBackPathEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, abilityStatusEventData); } REGISTER_AA(AmsStAbilityM1); diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/BUILD.gn old mode 100644 new mode 100755 index c11714f5ce4cf4c8ebacf837ba98bb9a2a7cb946..0656e4fd3646e1b951ca61af982bf7a19d98d771 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestNConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestN\"", @@ -49,6 +50,7 @@ ohos_shared_library("amsSystemTestN") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn1.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn1.cpp index db89ebb51c7b7d787da5759e84ba5615ac2e720c..862b20cc0b8f0dea0c48b5ba42fc0dc1f5819bca 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn1.cpp @@ -145,8 +145,8 @@ void AmsStAbilityN1::SendPath(const std::string &callBackPath) std::string abilityStatus = pageAbilityEvent.GetAbilityStatus(std::to_string(Ability::GetState())); std::string callBackPathEventData = Ability::GetAbilityName() + callBack; std::string abilityStatusEventData = Ability::GetAbilityName() + abilityStatus; - pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::eventCode, callBackPathEventData); - pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::eventCode, abilityStatusEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, callBackPathEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, abilityStatusEventData); } REGISTER_AA(AmsStAbilityN1); diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn2.cpp index 0ce3b2fe7b2d7dbe66ee23c0a6459331eca4d638..374c494894e1caabeddbc328bdd6d279127b2838 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn2.cpp @@ -145,8 +145,8 @@ void AmsStAbilityN2::SendPath(const std::string &callBackPath) std::string abilityStatus = pageAbilityEvent.GetAbilityStatus(std::to_string(Ability::GetState())); std::string callBackPathEventData = Ability::GetAbilityName() + callBack; std::string abilityStatusEventData = Ability::GetAbilityName() + abilityStatus; - pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::eventCode, callBackPathEventData); - pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::eventCode, abilityStatusEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, callBackPathEventData); + pageAbilityEvent.PublishEvent(STEventName::g_eventName, STEventName::g_defeventCode, abilityStatusEventData); } REGISTER_AA(AmsStAbilityN2); diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn4.cpp index ad353add7cd90d3ce550fc68c58fb04d703d6b06..b9618f49ed4cc192205af1c0a120fce3967a4245 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn4.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestN/src/amsstabilityn4.cpp @@ -30,8 +30,6 @@ void AmsStAbilityN4::OnStart(const Want &want) void AmsStAbilityN4::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityN4::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityN4::OnNewWant(const Want &want) void AmsStAbilityN4::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityN4::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/BUILD.gn old mode 100644 new mode 100755 index dd3df12a8b0dad3fb961ecdd6bb181b8d487a42b..162f94a38db5581de2d25d366fd4442e27b9f955 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestO/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestOConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestO\"", @@ -46,6 +47,7 @@ ohos_shared_library("amsSystemTestO") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/BUILD.gn old mode 100644 new mode 100755 index 1cd342493356d5ec76e05d7866395a7ed5b43cc9..31fb4a8831f08c86e1ac7b43c688596dc8ca85f9 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestP/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestPConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestP\"", @@ -46,6 +47,7 @@ ohos_shared_library("amsSystemTestP") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/BUILD.gn old mode 100644 new mode 100755 index 713895c4574fdb0e3a9d1ff1ec808f3cf0cf9213..7e1a479fbc8e4e100fd0488367d1ad0fbb38efdf --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestQConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestQ\"", @@ -49,6 +50,7 @@ ohos_shared_library("amsSystemTestQ") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq4.cpp index 401b627482a9daa74178e03a198bfd441f8087b9..ae8b01fe01685ab8423d45cfb7c347d15928d789 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq4.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestQ/src/amsstabilityq4.cpp @@ -30,8 +30,6 @@ void AmsStAbilityQ4::OnStart(const Want &want) void AmsStAbilityQ4::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityQ4::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityQ4::OnNewWant(const Want &want) void AmsStAbilityQ4::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityQ4::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/BUILD.gn old mode 100644 new mode 100755 index ee162705375395f7bab6d497dd5039b856cb80db..86d3609947f4dbe19fc71833f8314fa167f816dd --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestRConfig") { "//foundation/appexecfwk/standard/common/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestR\"", @@ -49,6 +50,7 @@ ohos_shared_library("amsSystemTestR") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr4.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr4.cpp index f21103e45040495c986e9cdbe6ce9e267ef3e87a..67730c5649c84b0365fb0a4dd85115442c52583c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr4.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr4.cpp @@ -30,8 +30,6 @@ void AmsStAbilityR4::OnStart(const Want &want) void AmsStAbilityR4::OnNewWant(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityR4::OnNewWant"); Ability::OnNewWant(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnNewWant; @@ -40,8 +38,6 @@ void AmsStAbilityR4::OnNewWant(const Want &want) void AmsStAbilityR4::OnForeground(const Want &want) { - GetWantInfo(want); - APP_LOGI("AmsStAbilityR4::OnForeground"); Ability::OnForeground(want); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnForeground; diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/BUILD.gn index 8b82e60c477e2e854e272143c8f39ae46802ebaf..467fc0932c7e688911119fc6e040eda34b230d88 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceA/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceA\"", diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/BUILD.gn index 73d83f5a5a21242744834da96a4a5887c877b882..f8e4c963a11d3ed6627998de8da8d277ae5011d7 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceB/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceB\"", @@ -47,6 +48,7 @@ ohos_shared_library("amsSystemTestServiceB") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/BUILD.gn index 8c918f78fd3fb75697dd2a1e6c5fef773d8be0a0..d008b65088a3150fe5377a2f93305ed90f17fdbe 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceC/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceC\"", @@ -43,6 +44,7 @@ ohos_shared_library("amsSystemTestServiceC") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/BUILD.gn index 8ff0c393022e5d79bbd91e17079ab2f27a0ec794..6dbee49c3907fa271e02329a1b00a4b874e900de 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceD/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceD\"", @@ -45,6 +46,7 @@ ohos_shared_library("amsSystemTestServiceD") { "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/BUILD.gn index 916afa438a92b2744deb61398a9d4689acc32992..4cc06d2eed3c960532839eb595e1994fe06d8c5c 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceE/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceE\"", @@ -45,6 +46,7 @@ ohos_shared_library("amsSystemTestServiceE") { "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/BUILD.gn index ab187939ff45692d1cc31a58a2d3f5a93de23349..88dc52b8765ea11ad9bbee98f3fa23d53dd753a3 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceF/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceF\"", @@ -44,6 +45,7 @@ ohos_shared_library("amsSystemTestServiceF") { "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/BUILD.gn index 4f0aaca9fa58591080368f09f877ae4ada7f4802..7d6d5f4260c4794a709e7f8e3c3c0e4ed2b8e878 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceG/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceG\"", @@ -45,6 +46,7 @@ ohos_shared_library("amsSystemTestServiceG") { "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/BUILD.gn index 0974c7d7d5a8f0ca0c551d84244d81152de986dc..1b4a8adef8ce937801f9ef74176585af503ae150 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestServiceH/BUILD.gn @@ -26,6 +26,7 @@ config("amsSystemTestCConfig") { "${aafwk_path}/services/abilitymgr/include", "${appexecfwk_path}/common/log/include", "//foundation/distributedschedule/services/dtbschedmgr/include", + "//third_party/jsoncpp/include", ] defines = [ "APP_LOG_TAG = \"amsSystemTestServiceH\"", @@ -45,6 +46,7 @@ ohos_shared_library("amsSystemTestServiceH") { "${appexecfwk_path}/kits:appkit_native", "${appexecfwk_path}/services/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h b/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h index 639bed97d3927af44c6ff496a07dadb41d6f9e18..6d178531b3ffbf888714b699a546b15798338de7 100644 --- a/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h +++ b/test/resource/amssystemtestability/abilitySrc/common/ability_append_test_info.h @@ -30,10 +30,50 @@ const std::string g_EVENT_REQU_SECOND = "requ_com_ohos_amsst_appkit_second"; const std::string g_EVENT_RESP_SECOND = "resp_com_ohos_amsst_appkit_second"; const std::string g_EVENT_RESP_SECOND_LIFECYCLE = "resp_com_ohos_amsst_appkit_second_lifecycle"; +const std::string g_EVENT_REQU_THIRD = "requ_com_ohos_amsst_appkit_third"; +const std::string g_EVENT_RESP_THIRD = "resp_com_ohos_amsst_appkit_third"; +const std::string g_EVENT_RESP_THIRD_LIFECYCLE = "resp_com_ohos_amsst_appkit_third_lifecycle"; + +const std::string g_EVENT_REQU_FOURTH = "requ_com_ohos_amsst_appkit_fourth"; +const std::string g_EVENT_RESP_FOURTH = "resp_com_ohos_amsst_appkit_fourth"; +const std::string g_EVENT_RESP_FOURTH_LIFECYCLE = "resp_com_ohos_amsst_appkit_fourth_lifecycle"; + +const std::string g_EVENT_REQU_FIFTH = "requ_com_ohos_amsst_appkit_fifth"; +const std::string g_EVENT_RESP_FIFTH = "resp_com_ohos_amsst_appkit_fifth"; +const std::string g_EVENT_RESP_FIFTH_LIFECYCLE = "resp_com_ohos_amsst_appkit_fifth_lifecycle"; + +const std::string g_EVENT_REQU_SIXTH = "requ_com_ohos_amsst_appkit_sixth"; +const std::string g_EVENT_RESP_SIXTH = "resp_com_ohos_amsst_appkit_sixth"; +const std::string g_EVENT_RESP_SIXTH_LIFECYCLE = "resp_com_ohos_amsst_appkit_sixth_lifecycle"; + +const std::string g_EVENT_REQU_MAIN = "requ_com_ohos_amsst_appkit_main"; +const std::string g_EVENT_RESP_MAIN = "resp_com_ohos_amsst_appkit_main"; +const std::string g_EVENT_RESP_MAIN_LIFECYCLE = "resp_com_ohos_amsst_appkit_main_lifecycle"; + +const std::string g_EVENT_REQU_MAIN_SUBSIDIARY = "requ_com_ohos_amsst_appkit_main_subsidiary"; +const std::string g_EVENT_RESP_MAIN_SUBSIDIARY = "resp_com_ohos_amsst_appkit_main_subsidiary"; +const std::string g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY = "resp_com_ohos_amsst_appkit_main_lifecycle_subsidiary"; + +const std::string g_EVENT_REQU_SECOND_SUBSIDIARY = "requ_com_ohos_amsst_appkit_second_subsidiary"; +const std::string g_EVENT_RESP_SECOND_SUBSIDIARY = "resp_com_ohos_amsst_appkit_second_subsidiary"; +const std::string g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY = "resp_com_ohos_amsst_appkit_second_lifecycle_subsidiary"; + const int MAIN_ABILITY_A_CODE = 100; const int SECOND_ABILITY_A_CODE = 200; const int MAIN_ABILITY_B_CODE = 300; +const int EXPECT_ST_ZERO = 0; + +const int MAIN_ABILITY_CODE = 100; +const int SECOND_ABILITY_CODE = 200; +const int THIRD_ABILITY_CODE = 300; +const int FOURTH_ABILITY_CODE = 400; +const int FIFTH_ABILITY_CODE = 500; +const int SIXTH_ABILITY_CODE = 600; + +const int MAIN_ABILITY_CODE_SUBSIDIARY = 10100; +const int SECOND_ABILITY_CODE_SUBSIDIARY = 10200; + enum class AppendApi { OnSetCaller, TerminateAndRemoveMisson, @@ -52,6 +92,17 @@ enum class AppendApi { End }; +enum class MissionStackApi { + LockMission = (int)AppendApi::End, + End +}; + +enum class TestAbilityState { + OnSaveAbilityState = (int)MissionStackApi::End, + OnRestoreAbilityState, + End +}; + } // namespace AppExecFwk } // namespace OHOS #endif // ABILITY_APPEND_TEST_INFO_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..82b131ef7d7027bb0f78b8f4034d349fc4cf63ec --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/serviceAbilityA" + +config("service_ability_a_config") { + visibility = [ ":*" ] + include_dirs = [ "${SUBDEMOSYSTEM_DIR}/include" ] + defines = [ + "APP_LOG_TAG = \"serviceAbilityA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("serviceAbilityA") { + sources = [ + "${SUBDEMOSYSTEM_DIR}/src/service_ability_a.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_ability_connect_callback_stub.cpp", + "${SUBDEMOSYSTEM_DIR}/src/test_ability_connection.cpp", + "${SUBDEMOSYSTEM_DIR}/src/verify_act_first_ability.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":service_ability_a_config" ] + deps = [ + "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/kits:appkit_native", + ] + external_deps = [ + "aafwk_standard:ability_manager", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + subsystem_name = "aafwk" + part_name = "aafwk_standard" +} diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/config.json b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9c9c80354726733eff631124bed5f69482f8ace8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/config.json @@ -0,0 +1,50 @@ +{ + "app":{ + "bundleName": "com.ix.ServiceAbility", + "vendor": "neusoft", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ix.ServiceAbility.src", + "name":"VerifyActFirstAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "ServiceAbilityA", + "moduleType": "entry" + }, + "abilities": [{ + "name": "VerifyActFirstAbility", + "icon": "$media:snowball", + "label": "VerifyActFirstAbility Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "page", + "visible": true + }, + { + "name": "ServiceAbilityA", + "icon": "$media:snowball", + "label": "Main Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true + } + ] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/service_ability_a.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/service_ability_a.h new file mode 100644 index 0000000000000000000000000000000000000000..be137c0be5436b400230e1b0e46a8c4902fc622d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/service_ability_a.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 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 _MAIN_SERVICE_ABILITY_H_ +#define _MAIN_SERVICE_ABILITY_H_ +#include "app_log_wrapper.h" +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "iremote_stub.h" +#include "want.h" +#include "ability.h" +#include "ability_loader.h" + +using Want = OHOS::AAFwk::Want; +namespace OHOS { +namespace AppExecFwk { + +class ServiceAbilityA : public Ability { +protected: + virtual void OnStart(const Want &want); + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId); + virtual sptr OnConnect(const Want &want); + virtual void OnDisconnect(const Want &want); + virtual void OnStop(); +}; + +class IServiceRemoteTest : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.ServiceRemoteTest"); + virtual int32_t ScheduleAdd(int32_t a, int32_t b) = 0; + virtual int32_t ScheduleSub(int32_t a, int32_t b) = 0; + enum { + // ipc id for OnAbilityConnectDone + ON_ABILITY_ADD = 0, + + // ipc id for OnAbilityDisConnectDone + ON_ABILITY_SUB + }; +}; + +class MockServiceRemoteTest : public IRemoteStub { +public: + MockServiceRemoteTest() = default; + virtual ~MockServiceRemoteTest() = default; + + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + return 0; + } + +private: + DISALLOW_COPY_AND_MOVE(MockServiceRemoteTest); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_MAIN_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_proxy.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..381cee206c5e52a5ecfb9e62d8e939e6506c6741 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_proxy.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 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_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_PROXY_H +#define OHOS_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_PROXY_H + +// #include "test_ability_connect_callback_interface.h" +#include "iremote_proxy.h" +#include "service_ability_a.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class AbilityConnectProxy + * AbilityConnect proxy. + */ +class TestAbilityConnectionProxy : public IRemoteProxy { +public: + explicit TestAbilityConnectionProxy(const sptr &impl) : IRemoteProxy(impl) + {} + + virtual ~TestAbilityConnectionProxy() + {} + + virtual int32_t ScheduleAdd(int32_t a, int32_t b) override; + virtual int32_t ScheduleSub(int32_t a, int32_t b) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_AAFWK_ABILITY_CONNECT_CALLBACK_PROXY_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_stub.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..642202feffddb2c5525f5e2a2e2b18eab9b9df40 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_stub.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 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_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_STUB_H +#define OHOS_AAFWK_TEST_ABILITY_CONNECT_CALLBACK_STUB_H + +#include +#include +#include "service_ability_a.h" +#include "nocopyable.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class TestAbilityConnectionStub + * AbilityConnect Stub. + */ +class TestAbilityConnectionStub : public IRemoteStub { +public: + TestAbilityConnectionStub(); + virtual ~TestAbilityConnectionStub(); + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + + // int32_t ScheduleAddInner(int32_t a, int32_t b); + // int32_t ScheduleSubInner(int32_t a, int32_t b); + +private: + DISALLOW_COPY_AND_MOVE(TestAbilityConnectionStub); +}; + +// /** +// * @class AbilityConnectCallbackRecipient +// * AbilityConnectCallbackRecipient notices IRemoteBroker died. +// */ +// class AbilityConnectCallbackRecipient : public IRemoteObject::DeathRecipient { +// public: +// using RemoteDiedHandler = std::function &)>; +// AbilityConnectCallbackRecipient(RemoteDiedHandler handler); +// virtual ~AbilityConnectCallbackRecipient(); +// virtual void OnRemoteDied(const wptr &remote); + +// private: +// RemoteDiedHandler handler_; +// }; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_AAFWK_ABILITY_CONNECT_CALLBACK_STUB_H diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connection.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connection.h new file mode 100644 index 0000000000000000000000000000000000000000..af2823577400c6cfd5e8b48981c5c76573cf26df --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connection.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 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 FOUNDATION_APPEXECFWK_TEST_ABILITY_THREAD_H +#define FOUNDATION_APPEXECFWK_TEST_ABILITY_THREAD_H + +#include "test_ability_connect_callback_stub.h" + +namespace OHOS { +namespace AppExecFwk { + +class TestAbilityConnection : public TestAbilityConnectionStub { +public: + /** + * @brief Default constructor used to create a AbilityThread instance. + */ + TestAbilityConnection(); + ~TestAbilityConnection(); + + /** + * @description: Provide operating system ConnectAbility information to the observer + * @param want Indicates the structure containing connect information about the ability. + */ + virtual int32_t ScheduleAdd(int32_t a, int32_t b) override; + virtual int32_t ScheduleSub(int32_t a, int32_t b) override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_ABILITY_THREAD_H \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h new file mode 100644 index 0000000000000000000000000000000000000000..d469f48b5fb44f7af2ed57b86eb7f97af32ea346 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 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 _VERIFY_ACT_FIRST_ABILITY_ +#define _VERIFY_ACT_FIRST_ABILITY_ +#include "ability_loader.h" +#include "common_event.h" +#include "app_log_wrapper.h" +#include "common_event_manager.h" +#include "ability_connect_callback_stub.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int CONNECT_SERVICE_ABILITY = 0; +const int DISCONNECT_SERVICE_ABILITY = 1; +const int START_SERVICE_ABILITY = 2; +const int STOP_SERVICE_ABILITY = 3; +} // namespace +class VerifyActFirstAbility : public Ability { +public: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; +}; +class VerifyIOAbilityLifecycleCallbacks : public AbilityLifecycleCallbacks { +public: + VerifyIOAbilityLifecycleCallbacks() = default; + virtual ~VerifyIOAbilityLifecycleCallbacks() = default; + + virtual void OnAbilityStart(const std::shared_ptr &ability); + virtual void OnAbilityInactive(const std::shared_ptr &ability); + virtual void OnAbilityBackground(const std::shared_ptr &ability); + virtual void OnAbilityForeground(const std::shared_ptr &ability); + virtual void OnAbilityActive(const std::shared_ptr &ability); + virtual void OnAbilityStop(const std::shared_ptr &ability); + virtual void OnAbilitySaveState(const PacMap &outState); +}; + +class AbilityContextStartAbilityTest : public EventFwk::CommonEventSubscriber { +public: + AbilityContextStartAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +}; +class ConnectServiceAbilityTest : public EventFwk::CommonEventSubscriber { +public: + ConnectServiceAbilityTest( + const EventFwk::CommonEventSubscribeInfo &sp, std::shared_ptr abilityContext, sptr conne) + : EventFwk::CommonEventSubscriber(sp) + { + abilityContext_ = abilityContext; + conne_ = conne; + }; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + std::shared_ptr abilityContext_ = nullptr; + sptr conne_ = nullptr; +}; +class AbilityConnectionActFirst : public AAFwk::AbilityConnectionStub { +public: + AbilityConnectionActFirst(){}; + virtual ~AbilityConnectionActFirst(){}; + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + static int onAbilityConnectDoneCount; + static int onAbilityDisconnectDoneCount; + static int test; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_VERIFY_ACT_FIRST_ABILITY_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/service_ability_a.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/service_ability_a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..de9c32781117ae8aceef68185db7838c0c4659e3 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/service_ability_a.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 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_ability_a.h" +// #include "app_log_wrapper.h" +// #include "iremote_broker.h" +// #include "iremote_object.h" +// #include "iremote_proxy.h" +// #include "iremote_stub.h" +// #include "main_service_ability.h" +#include "test_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { + +void ServiceAbilityA::OnStart(const Want &want) +{ + APP_LOGI("ServiceAbilityA OnStart"); + Ability::OnStart(want); +} +void ServiceAbilityA::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("ServiceAbilityA::OnCommand"); + Ability::OnCommand(want, restart, startId); +} +sptr ServiceAbilityA::OnConnect(const Want &want) +{ + APP_LOGI("ServiceAbilityA::OnConnect"); + sptr remoteObject = sptr(new (std::nothrow) TestAbilityConnection()); + + Ability::OnConnect(want); + return remoteObject->AsObject(); +} +void ServiceAbilityA::OnDisconnect(const Want &want) +{ + APP_LOGI("ServiceAbilityA::OnDisconnect"); + Ability::OnDisconnect(want); +} +void ServiceAbilityA::OnStop() +{ + APP_LOGI("ServiceAbilityA::OnStop"); + Ability::OnStop(); +} +REGISTER_AA(ServiceAbilityA); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connect_callback_stub.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connect_callback_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53fd3e123138fd632309236864a3be05354ff66a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connect_callback_stub.cpp @@ -0,0 +1,185 @@ + +/* + * Copyright (c) 2021 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 "test_ability_connect_callback_stub.h" + +#include "test_ability_connect_callback_proxy.h" +#include "hilog_wrapper.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +bool TestAbilityConnectionProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(TestAbilityConnectionProxy::GetDescriptor())) { + HILOG_ERROR("write interface token failed"); + return false; + } + return true; +} + +int32_t TestAbilityConnectionProxy::ScheduleAdd(int32_t a, int32_t b) +{ + HILOG_DEBUG("%s, a:%d,b:%d", __func__, a, b); + + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return -1; + } + + if (!data.WriteInt32(a)) { + HILOG_ERROR("connect done element error"); + return -1; + } + + if (!data.WriteInt32(b)) { + HILOG_ERROR("connect done element error"); + return -1; + } + + // if (!data.WriteParcelable(remoteObject)) { + // HILOG_ERROR("connect done remote object error"); + // return; + // } + + // if (!data.WriteInt32(resultCode)) { + // HILOG_ERROR("connect done result code error"); + // return; + // } + + error = Remote()->SendRequest(IServiceRemoteTest::ON_ABILITY_ADD, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("connect done fail, error: %d", error); + + int32_t result = 0; + if (!reply.ReadInt32(result)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + return result; + } + return -1; +} + +int32_t TestAbilityConnectionProxy::ScheduleSub(int32_t a, int32_t b) +{ + HILOG_DEBUG("%s, a:%d, b:%d", __func__, a, b); + int error; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + return -1; + } + // if (!data.WriteParcelable(&element) || !data.WriteInt32(resultCode)) { + // HILOG_ERROR("disconnect done data write error"); + // return; + // } + if (!data.WriteInt32(a)) { + HILOG_ERROR("connect done element error"); + return -1; + } + + if (!data.WriteInt32(b)) { + HILOG_ERROR("connect done element error"); + return -1; + } + error = Remote()->SendRequest(IServiceRemoteTest::ON_ABILITY_SUB, data, reply, option); + if (error != NO_ERROR) { + HILOG_ERROR("disconnect done fail, error: %d", error); + + int32_t result = 0; + if (!reply.ReadInt32(result)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + return result; + } + return -1; +} + +TestAbilityConnectionStub::TestAbilityConnectionStub() +{} + +TestAbilityConnectionStub::~TestAbilityConnectionStub() +{} + +int TestAbilityConnectionStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::u16string descriptor = TestAbilityConnectionStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + HILOG_INFO("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + + switch (code) { + case IServiceRemoteTest::ON_ABILITY_ADD: { + int a = 0; + if (!data.ReadInt32(a)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + + int b = 0; + if (!data.ReadInt32(b)) { + HILOG_ERROR("fail to ReadInt32 fd"); + } + + uint32_t res = ScheduleAdd(a, b); + reply.WriteInt32(res); + + return NO_ERROR; + } + // case IServiceRemoteTest::ON_ABILITY_SUB: { + // if (element == nullptr) { + // HILOG_ERROR("callback stub receive element is nullptr"); + // return ERR_INVALID_VALUE; + // } + // auto resultCode = data.ReadInt32(); + // OnAbilityDisconnectDone(*element, resultCode); + // delete element; + // return NO_ERROR; + // } + default: { + // if (element != nullptr) { + // delete element; + // } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } +} + +// void AbilityConnectCallbackRecipient::OnRemoteDied(const wptr &__attribute__((unused)) remote) +// { +// HILOG_ERROR("recv AbilityConnectCallbackRecipient death notice"); +// if (handler_) { +// handler_(remote); +// } +// } + +// AbilityConnectCallbackRecipient::AbilityConnectCallbackRecipient(RemoteDiedHandler handler) : handler_(handler) +// {} + +// AbilityConnectCallbackRecipient::~AbilityConnectCallbackRecipient() +// {} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connection.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f2d3688caa660a7961a3ed6d30842fe74802bfd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connection.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 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 "test_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +TestAbilityConnection::TestAbilityConnection() +{} +TestAbilityConnection::~TestAbilityConnection() +{} + +int32_t TestAbilityConnection::ScheduleAdd(int32_t a, int32_t b) +{ + return a + b; +} + +int32_t TestAbilityConnection::ScheduleSub(int32_t a, int32_t b) +{ + return a - b; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/verify_act_first_ability.cpp b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/verify_act_first_ability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..555ad8d1121a10c4ffaad3e38578427591b6f7c7 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/verify_act_first_ability.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2021 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 "verify_act_first_ability.h" +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +void AbilityConnectionActFirst::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("AbilityConnectionActFirst OnAbilityConnectDone resultCode: %{public}d", resultCode); + APP_LOGI("AbilityConnectionActFirst OnAbilityConnectDone %{public}s", element.GetAbilityName().c_str()); + APP_LOGI("AbilityConnectionActFirst OnAbilityConnectDone %{public}p", remoteObject.GetRefPtr()); +} + +void AbilityConnectionActFirst::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + APP_LOGI("AbilityConnectionActFirst OnAbilityDisconnectDone resultCode: %{public}d", resultCode); + APP_LOGI("AbilityConnectionActFirst OnAbilityDisconnectDone : %{public}s", element.GetAbilityName().c_str()); +} +void VerifyIOAbilityLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilityStart called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityInactive(const std::shared_ptr &ability) +{ + APP_LOGI( + "----------VerifyIOAbilityLifecycleCallbacks::OnAbilityInactive called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityBackground(const std::shared_ptr &ability) +{ + APP_LOGI( + "----------VerifyIOAbilityLifecycleCallbacks::OnAbilityBackground called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityForeground(const std::shared_ptr &ability) +{ + APP_LOGI( + "----------VerifyIOAbilityLifecycleCallbacks::OnAbilityForeground called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityActive(const std::shared_ptr &ability) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilityActive called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} + +void VerifyIOAbilityLifecycleCallbacks::OnAbilityStop(const std::shared_ptr &ability) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilityStop called. AbilityName is %{public}s----------", + ability->GetAbilityName().c_str()); +} +void VerifyIOAbilityLifecycleCallbacks::OnAbilitySaveState(const PacMap &outState) +{ + APP_LOGI("----------VerifyIOAbilityLifecycleCallbacks::OnAbilitySaveState called.----------"); +} + +void VerifyActFirstAbility::OnStart(const Want &want) +{ + APP_LOGI("----------VerifyActFirstAbility::onStart begin----------"); + std::shared_ptr callback = std::make_shared(); + Ability::GetApplication()->RegisterAbilityLifecycleCallbacks(callback); + + EventFwk::MatchingSkills MatchingSkillsFirst; + MatchingSkillsFirst.AddEvent("Test_AbilityContextStartAbility"); + EventFwk::CommonEventSubscribeInfo subscriberInfoFirst(MatchingSkillsFirst); + std::shared_ptr subscriberFirst = + std::make_shared(subscriberInfoFirst); + EventFwk::CommonEventManager::SubscribeCommonEvent(subscriberFirst); + + EventFwk::MatchingSkills MatchingSkillsService; + MatchingSkillsService.AddEvent("Test_ServiceAbility"); + EventFwk::CommonEventSubscribeInfo subscriberInfoService(MatchingSkillsService); + sptr conne = new AbilityConnectionActFirst(); + std::shared_ptr serviceSubscriber = + std::make_shared(subscriberInfoService, Ability::GetContext(), conne); + EventFwk::CommonEventManager::SubscribeCommonEvent(serviceSubscriber); + APP_LOGI("----------VerifyActFirstAbility::onStart end----------"); + + Ability::OnStart(want); +} +void VerifyActFirstAbility::OnStop() +{ + APP_LOGI("----------VerifyActFirstAbility::onStop begin----------"); + APP_LOGI("----------VerifyActFirstAbility::onStop end----------"); + Ability::OnStop(); +} +void VerifyActFirstAbility::OnActive() +{ + APP_LOGI("----------VerifyActFirstAbility::OnActive begin----------"); + APP_LOGI("----------VerifyActFirstAbility::OnActive end----------"); + Ability::OnActive(); +} +void VerifyActFirstAbility::OnInactive() +{ + APP_LOGI("----------VerifyActFirstAbility::OnInactive begin----------"); + APP_LOGI("----------VerifyActFirstAbility::OnInactive end----------"); + Ability::OnInactive(); +} +void VerifyActFirstAbility::OnBackground() +{ + APP_LOGI("----------VerifyActFirstAbility::OnBackground begin----------"); + APP_LOGI("----------VerifyActFirstAbility::OnBackground end----------"); + Ability::OnBackground(); +} + +void AbilityContextStartAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest begin----------"); + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest start ability----------"); + auto abilityContext = std::make_shared(); + int requestCode = -1; + Want want; + std::string targetBundle = "com.ix.ServiceaAbility"; + std::string targetAbility = "MainServiceAbilityDemo"; + want.SetElementName(targetBundle, targetAbility); + abilityContext->StartAbility(want, requestCode); + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest start ability end----------"); + APP_LOGI("---------- VerifyActFirstAbility AbilityContextStartAbilityTest end----------"); +} + +void ConnectServiceAbilityTest::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + if (abilityContext_ == nullptr) { + APP_LOGI("----------ConnectServiceAbilityTest::OnReceiveEvent abilityContext_ == nullptr----------"); + return; + } + + Want want_service; + std::string targetBundle = "com.ix.ServiceaAbility"; + std::string targetAbility = "MainServiceAbilityDemo"; + want_service.SetElementName(targetBundle, targetAbility); + switch (data.GetCode()) { + case CONNECT_SERVICE_ABILITY: { + auto ret = abilityContext_->ConnectAbility(want_service, conne_); + APP_LOGI("connect ability return %{public}d", ret); + break; + } + case DISCONNECT_SERVICE_ABILITY: { + abilityContext_->DisconnectAbility(conne_); + break; + } + case START_SERVICE_ABILITY: { + abilityContext_->StartAbility(want_service, 0); + break; + } + case STOP_SERVICE_ABILITY: { + auto ret = abilityContext_->StopAbility(want_service); + APP_LOGI("stop ability return %{public}d", ret); + break; + } + default: + APP_LOGI("---------- ConnectServiceAbilityTest OnReceiveEvent default----------"); + break; + } +} +REGISTER_AA(VerifyActFirstAbility) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/BUILD.gn old mode 100644 new mode 100755 index ef9b7a1b1e7fe51dd290d10628b9812e21b4dd6a..d1844161554c25acf9d7477c9cd3f58957da9352 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/BUILD.gn @@ -28,7 +28,7 @@ config("taskDispatcherTestAConfig") { "${common_path}/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", - + "//third_party/jsoncpp/include", "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/include", ] defines = [ @@ -61,6 +61,7 @@ ohos_shared_library("taskDispatcherTestA") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/BUILD.gn old mode 100644 new mode 100755 index f5a8a5243f2bc20c85f5d918b383a42d515564a0..aebce0fdfc079dc084a97d9a73c444aa5aa801d8 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/BUILD.gn @@ -28,7 +28,7 @@ config("taskDispatcherTestBConfig") { "${common_path}/log/include", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "${SUBST_TOOLS_DIR}/include", - + "//third_party/jsoncpp/include", "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/include", ] defines = [ @@ -61,6 +61,7 @@ ohos_shared_library("taskDispatcherTestB") { "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h index aa2709a5d990518c2b8a93db06317479b693bef9..0ac76a4b9f5284961ae275fdef5935d2f101d38e 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h @@ -22,12 +22,15 @@ #include "common_event_manager.h" #include "ability_loader.h" #include "app_log_wrapper.h" +#include "ability_manager.h" +#include "running_process_info.h" namespace OHOS { namespace AppExecFwk { namespace STEventName { const std::string g_eventName = "resp_st_page_ability_callback"; +const std::string g_eventNameProcessMemory = "resp_st_process_memory_info"; const std::string g_pidEventName = "resp_st_page_ability_pid_callback"; const std::string g_abilityStateInit = ":Init"; const std::string g_abilityStateOnStart = ":OnStart"; @@ -40,8 +43,22 @@ const std::string g_abilityStateOnNewWant = ":OnNewWant"; const std::string g_abilityStateOnCommand = ":OnCommand"; const std::string g_abilityStateOnConnect = ":OnConnect"; const std::string g_abilityStateOnDisconnect = ":OnDisconnect"; -const int eventCode = 0; -const std::vector g_eventList = {"requ_page_ability_terminate"}; +const std::string g_abilityStateInsert = ":Insert"; +const std::string g_abilityStateDelete = ":Delete"; +const std::string g_abilityStateUpdate = ":Update"; +const std::string g_abilityStateQuery = ":Query"; +const std::string g_abilityStateGetFileTypes = ":GetFileTypes"; +const std::string g_abilityStateOpenFile = ":OpenFile"; +const std::string g_getWantAgentState = ":GetWantAgentFail"; +const std::string g_triggerWantAgentState = ":TriggerWantAgentSuccess"; +const int g_defeventCode = 0; +const std::vector g_eventList = { + "requ_page_ability_terminate", + "requ_get_process_memory_info", + "requ_disconnect_service", + "requ_page_ability_terminate_caller", + "requ_page_ability_terminate_result", +}; static constexpr uint32_t LOAD_TIMEOUT = 500; // ms static constexpr uint32_t ACTIVE_TIMEOUT = 5000; // ms static constexpr uint32_t INACTIVE_TIMEOUT = 500; // ms @@ -56,15 +73,19 @@ static constexpr uint32_t RESTART_TIMEOUT = 5000; // ms class STPageAbilityEventSubscriber : public EventFwk::CommonEventSubscriber { public: - STPageAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, const std::shared_ptr &ability) - : CommonEventSubscriber(sp), ability_(std::move(ability)) + STPageAbilityEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, std::shared_ptr ability, + sptr &stub) + : CommonEventSubscriber(sp), ability_(ability), stub_(stub) {} ~STPageAbilityEventSubscriber() {} virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + std::string RunningProcessInfoToString(std::vector &infos); + bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); private: - std::shared_ptr ability_; + std::weak_ptr ability_; + wptr stub_; }; class STPageAbilityEvent { @@ -73,8 +94,9 @@ public: STPageAbilityEvent(const std::string &className); ~STPageAbilityEvent() = default; - bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); - void SubscribeEvent(std::vector eventList, const std::shared_ptr &ability); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void SubscribeEvent(std::vector eventList, std::shared_ptr ability, + sptr stub = nullptr); void UnsubscribeEvent(); std::string GetEventDate(const std::string &stateCallbackCount); std::string GetCallBackPath(const std::string &callBackPath); diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp index 3016490db6fd9bc38c6f2002ce545546c35b36e8..92e46f510c87a214497cb3ac4a7d16c8acdb935c 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp @@ -36,7 +36,8 @@ bool STPageAbilityEvent::PublishEvent(const std::string &eventName, const int &c return CommonEventManager::PublishCommonEvent(commonData); } -void STPageAbilityEvent::SubscribeEvent(std::vector eventList, const std::shared_ptr &ability) +void STPageAbilityEvent::SubscribeEvent( + std::vector eventList, std::shared_ptr ability, sptr stub) { MatchingSkills matchingSkills; for (const auto &e : eventList) { @@ -44,7 +45,7 @@ void STPageAbilityEvent::SubscribeEvent(std::vector eventList, cons } CommonEventSubscribeInfo subscribeInfo(matchingSkills); subscribeInfo.SetPriority(1); - subscriber_ = std::make_shared(subscribeInfo, ability); + subscriber_ = std::make_shared(subscribeInfo, ability, stub); CommonEventManager::SubscribeCommonEvent(subscriber_); } @@ -136,13 +137,58 @@ void STPageAbilityEventSubscriber::OnReceiveEvent(const CommonEventData &data) APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); APP_LOGI("DataTestPageAEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); auto eventName = data.GetWant().GetAction(); + if (!this->ability_.lock()) { + APP_LOGI("STPageAbilityEventSubscriber:ability_ is nullptr"); + } if (eventName.compare("requ_page_ability_terminate") == 0) { std::string target = data.GetData(); - if (target.compare(this->ability_->GetAbilityName()) == 0) { - this->ability_->TerminateAbility(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + (this->ability_.lock())->TerminateAbility(); + } + } + if (eventName.compare("requ_get_process_memory_info") == 0) { + } + if (eventName.compare("requ_disconnect_service") == 0) { + std::string target = data.GetData(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + if (stub_.promote()) { + (this->ability_.lock())->DisconnectAbility(stub_.promote()); + } + APP_LOGI("GetMyProcessMemoryInfo:stub_ is nullptr"); + } + } + if (eventName.compare("requ_page_ability_terminate_caller") == 0) { + std::string target = data.GetData(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + int requestCode = data.GetCode(); + (this->ability_.lock())->TerminateAbility(requestCode); + } + } + if (eventName.compare("requ_page_ability_terminate_result") == 0) { + std::string target = data.GetData(); + int startId = data.GetCode(); + if (target.compare((this->ability_.lock())->GetAbilityName()) == 0) { + (this->ability_.lock())->TerminateAbilityResult(startId); } } } +std::string STPageAbilityEventSubscriber::RunningProcessInfoToString(std::vector &infos) +{ + std::string data = ""; + return data; +} + +bool STPageAbilityEventSubscriber::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/BUILD.gn b/test/resource/bmssystemtestability/abilitySrc/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ad795dfb93f114af8976c21925c71f3173dd97c0 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2021 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. + +group("bms_system_test_app") { + deps = [ + "thirdPageDemo1:page_ability_native1", + "thirdPageDemo2:page_ability_native2", + "thirdPageDemo3:page_ability_native3", + "thirdPageDemo4:page_ability_native4", + ] +} diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/BUILD.gn b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..622d4811cf7f23e5d88464cf223af343f7bb3464 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("third_page_demo1_config") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${kits_path}/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"thirdPageDemo1\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("page_ability_native1") { + sources = [ "${SUBDEMOSYSTEM_DIR}/src/pageAbilityDemo.cpp" ] + configs = [ ":third_page_demo1_config" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${kits_path}:appkit_native", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "bmssystemtestability" +} diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/config.json b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9d69d4042c9e1d43baaf1d47026d19869d11eec6 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/config.json @@ -0,0 +1,52 @@ +{ + "app":{ + "bundleName": "com.third.hiworld.example1", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.third.hiworld.example.h1", + "name":"bmsThirdBundle1", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "PageAbilityDemo", + "icon": "$media:snowball", + "label": "bmsThirdBundle_A1 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/include/pageAbilityDemo.h b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/include/pageAbilityDemo.h new file mode 100644 index 0000000000000000000000000000000000000000..dad87b1f32774290063b4c66f7dee2842410b712 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/include/pageAbilityDemo.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 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 _PAGE_ABILITY_DEMO_ +#define _PAGE_ABILITY_DEMO_ +#include + +#include "ability.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "stpageabilityevent.h" + +namespace OHOS { +namespace AppExecFwk { +class PageAbilityDemo : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +public: + void CreateFile(const std::string &path) const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_PAGE_ABILITY_DEMO_ \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00a3c081aefd04e4aa4c3afbfaae471d3b9ef312 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2021 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 "pageAbilityDemo.h" +#include +#include +namespace OHOS { +namespace AppExecFwk { +const std::string BUNDLE_DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; +void PageAbilityDemo::OnStart(const Want &want) +{ + APP_LOGI("PageAbilityDemo::onStart"); + Ability::OnStart(want); + const std::string appName = "com.third.hiworld.example1"; + const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/name1.txt"; + const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/name2.txt"; + CreateFile(testCacheFileNamE1); + CreateFile(testCacheFileNamE2); +} + +void PageAbilityDemo::OnNewWant(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnNewWant"); + Ability::OnNewWant(want); +} + +void PageAbilityDemo::OnForeground(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnForeground"); + Ability::OnForeground(want); +} + +void PageAbilityDemo::OnStop() +{ + APP_LOGI("PageAbilityDemo::onStop"); + Ability::OnStop(); +} + +void PageAbilityDemo::OnActive() +{ + APP_LOGI("PageAbilityDemo::OnActive"); + Ability::OnActive(); +} + +void PageAbilityDemo::OnInactive() +{ + APP_LOGI("PageAbilityDemo::OnInactive"); + Ability::OnInactive(); +} + +void PageAbilityDemo::OnBackground() +{ + APP_LOGI("PageAbilityDemo::OnBackground"); + Ability::OnBackground(); +} + +void PageAbilityDemo::CreateFile(const std::string &path) const +{ + if (path.size() > PATH_MAX) { + APP_LOGE("CreateFile the length of path is too long"); + return; + } + + std::string realPath; + realPath.reserve(PATH_MAX); + realPath.resize(PATH_MAX - 1); + + if (realpath(path.c_str(), &(realPath[0])) == nullptr) { + APP_LOGW("CreateFile-translate:%{public}s not exist path", realPath.c_str()); + } + + std::ofstream file(path); + file.close(); + + if (access(realPath.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); + } +} + +REGISTER_AA(PageAbilityDemo) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/BUILD.gn b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..0c29a4fca2b978a28141789718c63a845af94220 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("third_page_demo2_config") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${kits_path}/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"thirdPageDemo2\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("page_ability_native2") { + sources = [ "${SUBDEMOSYSTEM_DIR}/src/pageAbilityDemo.cpp" ] + configs = [ ":third_page_demo2_config" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${kits_path}:appkit_native", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "bmssystemtestability" +} diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/config.json b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/config.json new file mode 100644 index 0000000000000000000000000000000000000000..58ace73872728cf283fdaf394c86127d92743d22 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/config.json @@ -0,0 +1,61 @@ +{ + "app":{ + "bundleName": "com.third.hiworld.example2", + "vendor": "example", + "version": { + "code": 2, + "name": "2.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.third.hiworld.example.h1", + "name":"bmsThirdBundle1", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "PageAbilityDemo", + "icon": "$media:snowball", + "label": "bmsThirdBundle_A2 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + }, + { + "name": "bmsThirdBundle_A2", + "icon": "$media:snowball", + "label": "bmsThirdBundle_A2 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true + } + ] + } +} \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/include/pageAbilityDemo.h b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/include/pageAbilityDemo.h new file mode 100644 index 0000000000000000000000000000000000000000..25e961d64614b9805890c5f31e43782df25c4f86 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/include/pageAbilityDemo.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 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 _PAGE_ABILITY_DEMO_ +#define _PAGE_ABILITY_DEMO_ +#include + +#include "ability.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "stpageabilityevent.h" +namespace OHOS { +namespace AppExecFwk { +class PageAbilityDemo : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +public: + void CreateDir(const std::string &path) const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_PAGE_ABILITY_DEMO_ \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/src/pageAbilityDemo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7422426a98b82e173d2579836e07596d25473b7 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo2/src/pageAbilityDemo.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 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 "pageAbilityDemo.h" +#include +namespace OHOS { +namespace AppExecFwk { +const std::string BUNDLE_DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; +void PageAbilityDemo::OnStart(const Want &want) +{ + APP_LOGI("PageAbilityDemo::onStart"); + Ability::OnStart(want); + const std::string appName = "com.third.hiworld.example2"; + const std::string testCacheDiR1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir1"; + const std::string testCacheDiR2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir2"; + CreateDir(testCacheDiR1); + CreateDir(testCacheDiR2); +} + +void PageAbilityDemo::OnNewWant(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnNewWant"); + Ability::OnNewWant(want); +} + +void PageAbilityDemo::OnForeground(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnForeground"); + Ability::OnForeground(want); +} + +void PageAbilityDemo::OnStop() +{ + APP_LOGI("PageAbilityDemo::onStop"); + Ability::OnStop(); +} + +void PageAbilityDemo::OnActive() +{ + APP_LOGI("PageAbilityDemo::OnActive"); + Ability::OnActive(); +} + +void PageAbilityDemo::OnInactive() +{ + APP_LOGI("PageAbilityDemo::OnInactive"); + Ability::OnInactive(); +} + +void PageAbilityDemo::OnBackground() +{ + APP_LOGI("PageAbilityDemo::OnBackground"); + Ability::OnBackground(); +} + +void PageAbilityDemo::CreateDir(const std::string &path) const +{ + if (access(path.c_str(), F_OK) != 0) { + if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) { + APP_LOGE("CreateDir:%{public}s error", path.c_str()); + } + } +} + +REGISTER_AA(PageAbilityDemo) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/BUILD.gn b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..c23607fc368bc5f8cac9ac83303599981c0f2b92 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("third_page_demo3_config") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${kits_path}/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"thirdPageDemo3\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("page_ability_native3") { + sources = [ "${SUBDEMOSYSTEM_DIR}/src/pageAbilityDemo.cpp" ] + configs = [ ":third_page_demo3_config" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${kits_path}:appkit_native", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "bmssystemtestability" +} diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/config.json b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9d69d4042c9e1d43baaf1d47026d19869d11eec6 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/config.json @@ -0,0 +1,52 @@ +{ + "app":{ + "bundleName": "com.third.hiworld.example1", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.third.hiworld.example.h1", + "name":"bmsThirdBundle1", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "PageAbilityDemo", + "icon": "$media:snowball", + "label": "bmsThirdBundle_A1 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/include/pageAbilityDemo.h b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/include/pageAbilityDemo.h new file mode 100644 index 0000000000000000000000000000000000000000..b70fe9b2b25570d6cb7f72dabbdb18bf1b2b2284 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/include/pageAbilityDemo.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 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 _PAGE_ABILITY_DEMO_ +#define _PAGE_ABILITY_DEMO_ +#include + +#include "ability.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "stpageabilityevent.h" +namespace OHOS { +namespace AppExecFwk { +class PageAbilityDemo : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +public: + void CreateFile(const std::string &path) const; + void CreateDir(const std::string &path) const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_PAGE_ABILITY_DEMO_ \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64984a03bebbd337590c56977cdaa20d1202a318 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2021 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 "pageAbilityDemo.h" +#include +#include +#include +namespace OHOS { +namespace AppExecFwk { +const std::string BUNDLE_DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; +void PageAbilityDemo::OnStart(const Want &want) +{ + APP_LOGI("PageAbilityDemo::onStart"); + Ability::OnStart(want); + const std::string appName = "com.third.hiworld.example1"; + std::string path = BUNDLE_DATA_ROOT_PATH + appName + "/cache/"; + APP_LOGI("PageAbilityDemo::CreateDir"); + for (int i = 1; i < 7; i++) { + path += "dir" + std::to_string(i) + "/"; + APP_LOGI("PageAbilityDemo::CreateDir %{public}s", path.c_str()); + CreateDir(path); + } + const std::string testCacheFileName = + BUNDLE_DATA_ROOT_PATH + appName + "/cache/dir1/dir2/dir3/dir4/dir5/dir6/name.txt"; + CreateFile(testCacheFileName); +} + +void PageAbilityDemo::OnNewWant(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnNewWant"); + Ability::OnNewWant(want); +} + +void PageAbilityDemo::OnForeground(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnForeground"); + Ability::OnForeground(want); +} + +void PageAbilityDemo::OnStop() +{ + APP_LOGI("PageAbilityDemo::onStop"); + Ability::OnStop(); +} + +void PageAbilityDemo::OnActive() +{ + APP_LOGI("PageAbilityDemo::OnActive"); + Ability::OnActive(); +} + +void PageAbilityDemo::OnInactive() +{ + APP_LOGI("PageAbilityDemo::OnInactive"); + Ability::OnInactive(); +} + +void PageAbilityDemo::OnBackground() +{ + APP_LOGI("PageAbilityDemo::OnBackground"); + Ability::OnBackground(); +} + +void PageAbilityDemo::CreateFile(const std::string &path) const +{ + if (path.size() > PATH_MAX) { + APP_LOGE("CreateFile the length of path is too long"); + return; + } + + std::string realPath; + realPath.reserve(PATH_MAX); + realPath.resize(PATH_MAX - 1); + + if (realpath(path.c_str(), &(realPath[0])) == nullptr) { + APP_LOGW("CreateFile-translate:%{public}s not exist path", realPath.c_str()); + } + + std::ofstream file(path); + file.close(); + + if (access(realPath.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); + } +} + +void PageAbilityDemo::CreateDir(const std::string &path) const +{ + if (access(path.c_str(), F_OK) != 0) { + if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) { + APP_LOGE("CreateDir:%{public}s error", path.c_str()); + } + } +} + +REGISTER_AA(PageAbilityDemo) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/BUILD.gn b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..743ec072b7c2df65733599508582cbc480f35810 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +SUBDEMOSYSTEM_DIR = "${appexecfwk_path}/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4" +SUBST_TOOLS_DIR = + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/tools" +config("third_page_demo4_config") { + visibility = [ ":*" ] + include_dirs = [ + "${SUBDEMOSYSTEM_DIR}/include", + "${kits_path}/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${innerkits_path}/libeventhandler/include", + "${services_path}/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${common_path}/log/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "${SUBST_TOOLS_DIR}/include", + "//third_party/jsoncpp/include", + ] + defines = [ + "APP_LOG_TAG = \"thirdPageDemo4\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("page_ability_native4") { + sources = [ "${SUBDEMOSYSTEM_DIR}/src/pageAbilityDemo.cpp" ] + configs = [ ":third_page_demo4_config" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${common_path}:libappexecfwk_common", + "${innerkits_path}/appexecfwk_base:appexecfwk_base", + "${innerkits_path}/appexecfwk_core:appexecfwk_core", + "${kits_path}:appkit_native", + "${services_path}/bundlemgr:libbms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "bmssystemtestability" +} diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/config.json b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9d69d4042c9e1d43baaf1d47026d19869d11eec6 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/config.json @@ -0,0 +1,52 @@ +{ + "app":{ + "bundleName": "com.third.hiworld.example1", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.third.hiworld.example.h1", + "name":"bmsThirdBundle1", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "PageAbilityDemo", + "icon": "$media:snowball", + "label": "bmsThirdBundle_A1 Ability", + "launchType": "singleton", + "orientation": "unspecified", + "type": "page", + "visible": true, + "skills": [ + { + "actions": [ + "ohos.aafwk.content.Want.ACTION_HOME" + ], + "entities": [ + "ohos.aafwk.content.Want.ENTITY_HOME" + ], + "attributes": [] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/include/pageAbilityDemo.h b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/include/pageAbilityDemo.h new file mode 100644 index 0000000000000000000000000000000000000000..b70fe9b2b25570d6cb7f72dabbdb18bf1b2b2284 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/include/pageAbilityDemo.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 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 _PAGE_ABILITY_DEMO_ +#define _PAGE_ABILITY_DEMO_ +#include + +#include "ability.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "stpageabilityevent.h" +namespace OHOS { +namespace AppExecFwk { +class PageAbilityDemo : public Ability { +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + + virtual void OnForeground(const Want &want) override; + virtual void OnNewWant(const Want &want) override; + +public: + void CreateFile(const std::string &path) const; + void CreateDir(const std::string &path) const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif //_PAGE_ABILITY_DEMO_ \ No newline at end of file diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afb14de6a493348b23a0ced32baf25d6222d9e81 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 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 "pageAbilityDemo.h" +#include +#include +#include +namespace OHOS { +namespace AppExecFwk { +const std::string BUNDLE_DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; +void PageAbilityDemo::OnStart(const Want &want) +{ + APP_LOGI("PageAbilityDemo::onStart"); + Ability::OnStart(want); + const std::string appName = "com.third.hiworld.example1"; + const std::string testCacheDir1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir1"; + const std::string testCacheDir2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir2"; + const std::string testCacheFileNamE1 = testCacheDir1 + "/name1.txt"; + const std::string testCacheFileNamE2 = testCacheDir2 + "/name2.txt"; + CreateDir(testCacheDir1); + CreateDir(testCacheDir2); + CreateFile(testCacheFileNamE1); + CreateFile(testCacheFileNamE2); +} + +void PageAbilityDemo::OnNewWant(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnNewWant"); + Ability::OnNewWant(want); +} + +void PageAbilityDemo::OnForeground(const Want &want) +{ + APP_LOGI("PageAbilityDemo::OnForeground"); + Ability::OnForeground(want); +} + +void PageAbilityDemo::OnStop() +{ + APP_LOGI("PageAbilityDemo::onStop"); + Ability::OnStop(); +} + +void PageAbilityDemo::OnActive() +{ + APP_LOGI("PageAbilityDemo::OnActive"); + Ability::OnActive(); +} + +void PageAbilityDemo::OnInactive() +{ + APP_LOGI("PageAbilityDemo::OnInactive"); + Ability::OnInactive(); +} + +void PageAbilityDemo::OnBackground() +{ + APP_LOGI("PageAbilityDemo::OnBackground"); + Ability::OnBackground(); +} + +void PageAbilityDemo::CreateFile(const std::string &path) const +{ + if (path.size() > PATH_MAX) { + APP_LOGE("CreateFile the length of path is too long"); + return; + } + + std::string realPath; + realPath.reserve(PATH_MAX); + realPath.resize(PATH_MAX - 1); + + if (realpath(path.c_str(), &(realPath[0])) == nullptr) { + APP_LOGW("CreateFile-translate:%{public}s not exist path", realPath.c_str()); + } + + std::ofstream file(path); + file.close(); + + if (access(realPath.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); + } +} + +void PageAbilityDemo::CreateDir(const std::string &path) const +{ + if (access(path.c_str(), F_OK) != 0) { + if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) { + APP_LOGE("CreateDir:%{public}s error", path.c_str()); + } + } +} + +REGISTER_AA(PageAbilityDemo) +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/bundlemgrsst/jsBundle/jsSystemBundle/bmsSystemBundle1.hap b/test/resource/bundlemgrsst/jsBundle/jsSystemBundle/bmsSystemBundle1.hap new file mode 100755 index 0000000000000000000000000000000000000000..310624e7c25895646397dc3385c0ca75e2835362 Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsSystemBundle/bmsSystemBundle1.hap differ diff --git a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle1.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle1.hap new file mode 100755 index 0000000000000000000000000000000000000000..c9347d5bdd34865a9041afd0d1cb8f63928a756b Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle1.hap differ diff --git a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle2.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle2.hap new file mode 100755 index 0000000000000000000000000000000000000000..747254f013c6c7bad054d686c2cb589c478ddfe3 Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle2.hap differ diff --git a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle3.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle3.hap new file mode 100755 index 0000000000000000000000000000000000000000..7c5833f39f7e877cf17f373c0b87a8bb0e1061b0 Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle3.hap differ diff --git a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle4.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle4.hap new file mode 100755 index 0000000000000000000000000000000000000000..fd9201f1b896e4e03af03cdc620f91514e8e4ccf Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle4.hap differ diff --git a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle5.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle5.hap new file mode 100755 index 0000000000000000000000000000000000000000..62349b1efeea5e9ffe1e9f84cc4f31807d532586 Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle5.hap differ diff --git a/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle6.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle6.hap new file mode 100755 index 0000000000000000000000000000000000000000..dab517b5a182b251899e1356b4904b251d97c6b8 Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundle6.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap index f5cb92e3b8e3f0aae8502ea5477529d0e11b0a54..41142715b101b06f9b6b3be03c60c319b6c05895 100644 Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap index 5c8f741ef6776ba4d31565fcf6c14f7623cce0d4..c7ec8bfd7f89debc0865b60f641c733f5765b694 100644 Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle25.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap new file mode 100644 index 0000000000000000000000000000000000000000..f0d31b0f7c15b20eb169c09f4f926a5a26d9a2b3 Binary files /dev/null and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle45.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle45.hap new file mode 100644 index 0000000000000000000000000000000000000000..3ff235b0601412ca8074fb38ab892df6f18c9da8 Binary files /dev/null and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle45.hap differ diff --git a/test/resource/formsystemtestability/BUILD.gn b/test/resource/formsystemtestability/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..48b23fa1259b5527045b8fbe2c27bde38f716951 --- /dev/null +++ b/test/resource/formsystemtestability/BUILD.gn @@ -0,0 +1,16 @@ +# Copyright (c) 2021 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. + +group("fms_system_test_app") { + deps = [ "formSystemTestServiceA:formSystemTestServiceA" ] +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a3b48e26782593bb028c22c004a8d63f3e1ca781 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +subdemosystem_path = "${appexecfwk_path}/test/resource/formsystemtestability/formSystemTestServiceA" +config("formSystemTestAConfig") { + visibility = [ ":*" ] + include_dirs = [ + "${subdemosystem_path}/include", + "${appexecfwk_path}/kits/appkit/native/app", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/services/bundlemgr/include", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "//foundation/distributedschedule/services/dtbschedmgr/include", + "${even_path}/cesfwk/innerkits/include", + "${even_path}/cesfwk/kits/native/include", + ] + defines = [ + "APP_LOG_TAG = \"formSystemTestServiceA\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("formSystemTestServiceA") { + sources = [ "${subdemosystem_path}/src/form_st_service_ability_a1.cpp" ] + configs = [ ":formSystemTestAConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/kits:appkit_native", + "${appexecfwk_path}/services/bundlemgr:libbms", + "//utils/native/base:utilsbase", + ] + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "formsystemtestability" +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/config.json b/test/resource/formsystemtestability/formSystemTestServiceA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f88dbdcf504e1285e7835194c30ca94bb0391b35 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/config.json @@ -0,0 +1,87 @@ +{ + "app": { + "bundleName": "com.provider.bundleName1", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package": "com.provider.FormSystemTestServiceA.src", + "name": "moduleName11", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "FormStServiceAbilityA1", + "icon": "$media:snowball", + "label": "FormStServiceAbilityA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true, + "formsEnabled": true, + "forms": [ + { + "name": "formName111", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "landscapeLayouts": [""], + "portraitLayouts": [""], + "updateEnabled": true, + "scheduledUpateTime": "10:30", + "updateDuration": 1, + "deepLink": "", + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "defPermissions": [ + { + "name": "com.permission.CAMERA", + "grantMode": "system_grant", + "availableScope": ["signature"], + "label": "CAMERA permission", + "description": "CAMERA permission in detail" + } + ], + "js": [ + { + "name": "card", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h new file mode 100644 index 0000000000000000000000000000000000000000..d50f4f3bc4da5b6309ef572c1c4b1be04333a10b --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 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 FORM_ST_SERVICE_ABILITY_A1_ +#define FORM_ST_SERVICE_ABILITY_A1_ +#include +#include +#include "ability_connect_callback_stub.h" +#include "ability_connect_callback_proxy.h" +#include "ability_loader.h" +#include "common_event.h" +#include "common_event_manager.h" + +#include "form_provider_info.h" + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; +const std::string APP_A1_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_a1"; +const std::string APP_A1_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_a1"; + +class FormStServiceAbilityA1 : public Ability { +public: + ~FormStServiceAbilityA1(); + +protected: + virtual void OnStart(const Want &want) override; + virtual void OnStop() override; + virtual void OnActive() override; + virtual void OnInactive() override; + virtual void OnBackground() override; + virtual void OnNewWant(const Want &want) override; + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + virtual sptr OnConnect(const Want &want) override; + virtual void OnDisconnect(const Want &want) override; + virtual FormProviderInfo OnCreateForm(const Want &want) override; + +private: + void Clear(); + void GetWantInfo(const Want &want); + std::vector Split(std::string str, const std::string &token); + bool SubscribeEvent(); + static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); + void StartOtherAbility(); + void ConnectOtherAbility(); + void DisConnectOtherAbility(); + void StopSelfAbility(); + + std::string shouldReturn_ = {}; + std::string targetBundle_ = {}; + std::string targetAbility_ = {}; + std::string nextTargetBundle_ = {}; + std::string nextTargetAbility_ = {}; + std::string targetBundleConn_ = {}; + std::string targetAbilityConn_ = {}; + std::string nextTargetBundleConn_ = {}; + std::string nextTargetAbilityConn_ = {}; + std::string zombie_ = {}; + + typedef void (FormStServiceAbilityA1::*func)(); + static std::map funcMap_; + class AbilityConnectCallback; + sptr stub_ = {}; + sptr connCallback_ = {}; + class AppEventSubscriber; + std::shared_ptr subscriber_ = {}; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + sptr AsObject() override + { + return nullptr; + } + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount++; + PublishEvent(APP_A1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); + } + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + if (resultCode == 0) { + onAbilityConnectDoneCount--; + PublishEvent(APP_A1_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); + } + } + + static int onAbilityConnectDoneCount; + }; + class AppEventSubscriber : public EventFwk::CommonEventSubscriber { + public: + AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + ~AppEventSubscriber() = default; + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + + FormStServiceAbilityA1 *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_A1_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfe34180b5989830052433c54d296728e457686a --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2021 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 "form_st_service_ability_a1.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityA1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityA1::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityA1::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityA1::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityA1::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityA1::StopSelfAbility}, +}; + +FormStServiceAbilityA1::~FormStServiceAbilityA1() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityA1::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityA1::Split"); + + std::vector splitString; + while (str.size()) { + size_t index = str.find(token); + if (index != std::string::npos) { + splitString.push_back(str.substr(0, index)); + str = str.substr(index + token.size()); + if (str.size() == 0) { + splitString.push_back(str); + } + } else { + splitString.push_back(str); + str = ""; + } + } + return splitString; +} +void FormStServiceAbilityA1::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA1::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityA1::StartOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + if (!targetBundle_.empty() && !targetAbility_.empty()) { + std::vector strtargetBundles = Split(targetBundle_, ","); + std::vector strTargetAbilitys = Split(targetAbility_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + StartAbility(want); + sleep(1); + } + } +} +void FormStServiceAbilityA1::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityA1::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityA1::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " + "nextTargetAbilityConn=%{public}s", + nextTargetBundleConn_.c_str(), + nextTargetAbilityConn_.c_str()); + + // connect service ability + if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { + std::vector strtargetBundles = Split(targetBundleConn_, ","); + std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); + for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { + Want want; + want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); + want.SetParam("shouldReturn", shouldReturn_); + want.SetParam("targetBundle", nextTargetBundle_); + want.SetParam("targetAbility", nextTargetAbility_); + want.SetParam("targetBundleConn", nextTargetBundleConn_); + want.SetParam("targetAbilityConn", nextTargetAbilityConn_); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + APP_LOGI("FormStServiceAbilityA1::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityA1::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityA1::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA1::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityA1::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityA1::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityA1::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityA1::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA1::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityA1::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityA1::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityA1::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA1::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityA1::OnStop() +{ + APP_LOGI("FormStServiceAbilityA1::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityA1::OnActive() +{ + APP_LOGI("FormStServiceAbilityA1::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityA1::OnInactive() +{ + APP_LOGI("FormStServiceAbilityA1::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityA1::OnBackground() +{ + APP_LOGI("FormStServiceAbilityA1::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityA1::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityA1::GetWantInfo(const Want &want) +{ + Want mWant(want); + shouldReturn_ = mWant.GetStringParam("shouldReturn"); + targetBundle_ = mWant.GetStringParam("targetBundle"); + targetAbility_ = mWant.GetStringParam("targetAbility"); + targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); + targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); + nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); + nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); + nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); + nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); + zombie_ = mWant.GetStringParam("zombie"); + FormStServiceAbilityA1::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityA1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityA1::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + code, + data.c_str()); + + Want want; + want.SetAction(eventName); + CommonEventData commonData; + commonData.SetWant(want); + commonData.SetCode(code); + commonData.SetData(data); + return CommonEventManager::PublishCommonEvent(commonData); +} +sptr FormStServiceAbilityA1::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA1::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + formProviderClient->SetOwner(std::make_shared(*this)); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityA1::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA1::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A1_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityA1::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A1_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityA1::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityA1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A1_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityA1::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + } else { + if (mainAbility_ != nullptr) { + (mainAbility_->*funcMap_[dataContent])(); + } + } + } +} + +FormProviderInfo FormStServiceAbilityA1::OnCreateForm(const Want &want) +{ + APP_LOGI("%{public}s start", __func__); + FormProviderInfo formProviderInfo; + if (!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { + APP_LOGE("%{public}s, formId not exist", __func__); + return formProviderInfo; + } + std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + formProviderInfo.SetFormData(FormProviderData(std::string("{\"city\": \"beijingA\", \"formId\": " + formId + "}"))); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +REGISTER_AA(FormStServiceAbilityA1); +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/tools/bm/pageAbilityBundleForInstallNoSignature.hap b/test/resource/tools/bm/pageAbilityBundleForInstallNoSignature.hap new file mode 100644 index 0000000000000000000000000000000000000000..acd820c6bddb09ccb3bc08ed9faa8edb9865f4cf Binary files /dev/null and b/test/resource/tools/bm/pageAbilityBundleForInstallNoSignature.hap differ diff --git a/test/systemtest/common/ams/BUILD.gn b/test/systemtest/common/ams/BUILD.gn index b8671e39ca3b89315ce652b4cf74df3e1302dc10..af5964d1072ac13744f10dd58f98e91128c3dc31 100755 --- a/test/systemtest/common/ams/BUILD.gn +++ b/test/systemtest/common/ams/BUILD.gn @@ -32,10 +32,14 @@ group("systemtest") { deps = [ "ams_aa_command_test:systemtest", "ams_ability_append_test:systemtest", + "ams_ability_visible_test:systemtest", "ams_app_process_manage_test:systemtest", + + #"ams_configuration_updated_test:ams_configuration_updated_test", "ams_data_ability_test:systemtest", "ams_dfx_test:systemtest", "ams_kit_test:systemtest", + "ams_missionstack_test:ams_missionstack_test", "ams_page_ability_test:systemtest", "ams_power_test:systemtest", "ams_service_ability_test:systemtest", diff --git a/test/systemtest/common/ams/ams_aa_command_test/BUILD.gn b/test/systemtest/common/ams/ams_aa_command_test/BUILD.gn old mode 100644 new mode 100755 index 684690e1739fb1fb0b064855c1a9e4b500f875ce..8a75f96226cd1b39e1c19bf35b20054efaf05a2a --- a/test/systemtest/common/ams/ams_aa_command_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_aa_command_test/BUILD.gn @@ -23,6 +23,7 @@ ohos_systemtest("ams_aa_command_test") { "//foundation/aafwk/standard/tools/aa/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//foundation/distributedschedule/safwk/services/safwk/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -49,6 +50,7 @@ ohos_systemtest("ams_aa_command_test") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_ability_append_test/BUILD.gn b/test/systemtest/common/ams/ams_ability_append_test/BUILD.gn old mode 100644 new mode 100755 index 24e24e606804ac50264b9179273bb7040989db80..1f6c17236362249d656cfbf55d0d7530c8b1fbd2 --- a/test/systemtest/common/ams/ams_ability_append_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_ability_append_test/BUILD.gn @@ -21,6 +21,7 @@ ohos_systemtest("ams_ability_append_test") { "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -47,6 +48,7 @@ ohos_systemtest("ams_ability_append_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_ability_visible_test/BUILD.gn b/test/systemtest/common/ams/ams_ability_visible_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..3b4a98c8048e1d41975825a5de869f0dc89d5d5c --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_visible_test/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_ability_visible_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/system_test_ability_util.cpp", + "ams_ability_visible_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${appexecfwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_ability_visible_test" ] +} diff --git a/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0932a783d24df1e73bf0d3c9a3f3ea9559b03688 --- /dev/null +++ b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp @@ -0,0 +1,1266 @@ +/* + * Copyright (c) 2021 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 "hilog_wrapper.h" +#include "ability_connect_callback_proxy.h" +#include "ability_connect_callback_stub.h" +#include "ability_manager_service.h" +#include "ability_manager_errors.h" +#include "app_mgr_service.h" +#include "module_test_dump_util.h" +#include "system_test_ability_util.h" +#include "module_test_dump_util.h" +#include "sa_mgr_client.h" +#include "system_ability_definition.h" +#include "common_event.h" +#include "common_event_manager.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::MTUtil; +using namespace OHOS::STABUtil; +using namespace OHOS::EventFwk; + +namespace { +using MAP_STR_STR = std::map; +std::vector bundleNameSuffix = {"PageA", "ServiceB"}; +static const std::string bundleNameBase = "com.ohos.amsst.appAbilityVisible"; +static const std::string hapNameBase = "amsAbilityVisibleTest"; +static const std::string abilityNameBase = "AmsAbilityVisibleTest"; +static const std::string launcherBundle = "com.ix.launcher"; +static const std::string launcherAbility = "LauncherAbility"; +static const std::string systemUiBundle = "com.ohos.systemui"; +static const std::string terminateAbility = "requ_page_ability_terminate"; +static const std::string terminateAbilityCaller = "requ_page_ability_terminate_caller"; +static const std::string disconnectService = "requ_disconnect_service"; +static const std::string terminateAbilityResult = "requ_page_ability_terminate_result"; + +static const std::string DUMP_STACK_LIST = "--stack-list"; +static const std::string DUMP_SERVICE = "--serv"; +static const std::string DUMP_DATA = "--data"; +static const std::string DUMP_STACK = "--stack"; +static const std::string DUMP_MISSION = "--mission"; +static const std::string DUMP_TOP = "--top"; +static const std::string DUMP_ALL = "-a"; +static const std::string abilityStateInit = ":Init"; +static const std::string abilityStateOnStart = ":OnStart"; +static const std::string abilityStateOnStop = ":OnStop"; +static const std::string abilityStateOnActive = ":OnActive"; +static const std::string abilityStateOnInactive = ":OnInactive"; +static const std::string abilityStateOnBackground = ":OnBackground"; +static const std::string abilityStateOnForeground = ":OnForeground"; +static const std::string abilityStateOnNewWant = ":OnNewWant"; +static const std::string abilityStateOnCommand = ":OnCommand"; +static const std::string abilityStateOnConnect = ":OnConnect"; +static const std::string abilityStateOnDisconnect = ":OnDisconnect"; +static const std::string abilityStateInsert = ":Insert"; +static const std::string abilityStateDelete = ":Delete"; +static const std::string abilityStateUpdate = ":Update"; +static const std::string abilityStateQuery = ":Query"; +static const std::string abilityStateGetFileTypes = ":GetFileTypes"; +static const std::string abilityStateOpenFile = ":OpenFile"; +static const std::string getWantAgentState = ":GetWantAgentFail"; +static const std::string triggerWantAgentState = ":TriggerWantAgentSuccess"; +static const int abilityStateCountOne = 1; +static const int abilityStateCountTwo = 2; +enum AbilityState_Test { + INITIAL = 0, + INACTIVE, + ACTIVE, + BACKGROUND, + SUSPENDED, + INACTIVATING, + ACTIVATING, + MOVING_BACKGROUND, + TERMINATING, + ALLSUM, +}; +static const std::vector abilityStateVec = { + "INITIAL", + "INACTIVE", + "ACTIVE", + "BACKGROUND", + "SUSPENDED", + "INACTIVATING", + "ACTIVATING", + "MOVING_BACKGROUND", + "TERMINATING", +}; +} // namespace +class AppEventSubscriber; + +class AmsAbilityVisibleTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static std::vector GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs); + static bool SubscribeEvent(); + void ShowDump(); + static void CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, + const std::string &state, const std::string &midState); + void ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, + const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = (DUMP_STACK + " 1")); + void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum, const std::string &type = "-a"); + void ExpectServiceAbilityNumInStack(const std::string &abilityName, int abilityNum); + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) + {} + virtual ~AppEventSubscriber() + {} + virtual void OnReceiveEvent(const CommonEventData &data) override; + }; + + class AbilityConnectCallback : public AbilityConnectionStub { + public: + /** + * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element,.service ability's ElementName. + * @param remoteObject,.the session proxy of service ability. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityConnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount++; + } + resultConnectCode = resultCode; + } + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element,.service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override + { + GTEST_LOG_(INFO) << "AbilityConnectCallback::OnAbilityDisconnectDone:resultCode = " << resultCode; + if (resultCode == 0) { + onAbilityConnectDoneCount--; + } + resultConnectCode = resultCode; + } + + static size_t onAbilityConnectDoneCount; + static int resultConnectCode; + }; + static sptr appMs_; + static sptr abilityMs_; + static STtools::Event event_; + static std::shared_ptr subscriber_; + static int *memTestValue_; +}; + +sptr AmsAbilityVisibleTest::appMs_ = nullptr; +sptr AmsAbilityVisibleTest::abilityMs_ = nullptr; +STtools::Event AmsAbilityVisibleTest::event_ = STtools::Event(); +int *AmsAbilityVisibleTest::memTestValue_ = nullptr; +std::shared_ptr AmsAbilityVisibleTest::subscriber_ = nullptr; +size_t AmsAbilityVisibleTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +int AmsAbilityVisibleTest::AbilityConnectCallback::resultConnectCode = 0; + +void AmsAbilityVisibleTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::SetUpTestCase(void)"; + + SubscribeEvent(); + appMs_ = STAbilityUtil::GetAppMgrService(); + abilityMs_ = STAbilityUtil::GetAbilityManagerService(); + if (appMs_) { + appMs_->SetAppFreezingTime(60); + int time = 0; + appMs_->GetAppFreezingTime(time); + std::cout << "appMs_->GetAppFreezingTime();" << time << std::endl; + } +} + +void AmsAbilityVisibleTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::TearDownTestCase(void)"; + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +void AmsAbilityVisibleTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::SetUp(void)"; + std::vector hapNames = GetBundleNames(hapNameBase, bundleNameSuffix); + STAbilityUtil::InstallHaps(hapNames); +} + +void AmsAbilityVisibleTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::TearDown(void)"; + if (memTestValue_) { + delete[] memTestValue_; + } + + std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); + STAbilityUtil::UninstallBundle(bundleNames); + + STAbilityUtil::CleanMsg(event_); +} + +std::vector AmsAbilityVisibleTest::GetBundleNames( + const std::string &strBase, const std::vector &strSuffixs) +{ + std::vector bundleNames; + for (auto strSuffix : strSuffixs) { + bundleNames.push_back(strBase + strSuffix); + } + return bundleNames; +} + +bool AmsAbilityVisibleTest::SubscribeEvent() +{ + std::vector eventList = {"resp_st_page_ability_callback"}; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} + +void AmsAbilityVisibleTest::ShowDump() +{ + if (abilityMs_) { + std::vector dumpInfo; + abilityMs_->DumpState("-a", dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + dumpInfo.clear(); + abilityMs_->DumpState(DUMP_SERVICE, dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + dumpInfo.clear(); + abilityMs_->DumpState(DUMP_DATA, dumpInfo); + for (const auto &info : dumpInfo) { + std::cout << info << std::endl; + } + } +} + +void AmsAbilityVisibleTest::CheckAbilityStateByName(const std::string &abilityName, + const std::vector &info, const std::string &state, const std::string &midState) +{ + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", info, result); + auto pos = MTDumpUtil::GetInstance()->GetSpecific(abilityName, result, result.begin()); + // ability exist + EXPECT_NE(pos, result.end()); + MTDumpUtil::GetInstance()->GetAll("State", info, result); + EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } + // ability state + if (midState != "") { + bool compareResult = ((*pos == state) || (*pos == midState)); + EXPECT_EQ(1, compareResult); + } else { + EXPECT_EQ(*pos, state); + } +} + +void AmsAbilityVisibleTest::ExpectAbilityCurrentState(const std::string &abilityName, + const AbilityState_Test ¤tState, const AbilityState_Test &midState, const std::string &args) +{ + std::string strCurrentState = abilityStateVec.at(currentState); + std::string strMidState = ""; + if (midState != AbilityState_Test::ALLSUM) { + strMidState = abilityStateVec.at(midState); + } + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(args, dumpInfo); + CheckAbilityStateByName(abilityName, dumpInfo, strCurrentState, strMidState); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsAbilityVisibleTest::ExpectAbilityNumInStack( + const std::string &abilityName, int abilityNum, const std::string &type) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(type, dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsAbilityVisibleTest::ExpectServiceAbilityNumInStack(const std::string &abilityName, int abilityNum) +{ + std::vector dumpInfo; + if (abilityMs_ != nullptr) { + abilityMs_->DumpState(DUMP_SERVICE, dumpInfo); + std::vector result; + MTDumpUtil::GetInstance()->GetAll("AbilityName", dumpInfo, result); + // only one record in stack + EXPECT_EQ(abilityNum, std::count(result.begin(), result.end(), abilityName)); + } else { + HILOG_ERROR("ability manager service(abilityMs_) is nullptr"); + } +} + +void AmsAbilityVisibleTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + + std::string eventName = data.GetWant().GetAction(); + if (eventName == "resp_st_page_ability_callback") { + std::string target = data.GetData(); + STAbilityUtil::Completed(event_, target, data.GetCode()); + } +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0100 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : The test process starts an ability whose visible attribute is false + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0100 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA1"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + ErrCode result = STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(result, ABILITY_VISIBLE_FALSE_DENY_REQUEST); + + ExpectAbilityNumInStack(abilityName, 0); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0100 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0200 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : The test process starts an ability, + * and the visible attribute of the ability is the default value. + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0200, TestSize.Level2) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0200 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA4"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + ErrCode result = STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(result, ABILITY_VISIBLE_FALSE_DENY_REQUEST); + + ExpectAbilityNumInStack(abilityName, 0); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0200 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0300 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : The test process starts an ability whose visible attribute is true + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0300 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0300 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0400 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA1) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA1 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0400 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0400 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0500 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA3,type:singleton) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA3 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0500 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0500 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0600 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageB1) whose visible attribute is false + * 3.PageA2 has the different bundleName as PageB1 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0600 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0600 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0700 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageB2) whose visible attribute is true + * 3.PageA2 has the different bundleName as PageB2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0700 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0700 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0800 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts a Service ability(Service) whose visible attribute is false + * 3.PageA2 has the different bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0800, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0800 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0800 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_0900 + * @tc.name : Visible attribute impact on startAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) starts a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_0900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0900 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_0900 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1000 + * @tc.name : Visible attribute impact on ConnectAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageA2 has the different bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1000 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Service"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1000 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1100 + * @tc.name : Visible attribute impact on ConnectAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1100 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Service"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnConnect, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1100 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1200 + * @tc.name : Visible attribute impact on start dataAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) start a Data ability(Data) whose visible attribute is false + * 3.PageA2 has the different bundleName as Data + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1200 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Data"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Data"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_DATA); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1200 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1300 + * @tc.name : Visible attribute impact on start dataAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a Data ability(Data) whose visible attribute is false + * 3.PageB2 has the same bundleName as Data + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1300 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Data"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Data"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateInsert, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_DATA); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1300 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1400 + * @tc.name : Visible attribute impact on terminateAbility + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA3,type:singleton) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA3 + * 4.terminate PageA3 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1400 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1400 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1500 + * @tc.name : Visible attribute impact on terminateAbilityCaller + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) starts an ability(PageA3,type:singleton) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA3 + * 4.terminateCaller PageA2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1500 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA3"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbilityCaller, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1500 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1600 + * @tc.name : Visible attribute impact on terminateAbility + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.terminate Service and PageB2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1600 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName, 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1600 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1700 + * @tc.name : Visible attribute impact on terminateAbilityCaller + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.The ability(Service) start a Service ability(ServiceA1) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service and ServiceA1 + * 4.terminateCaller Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1700, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1700 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + std::string abilityName3 = abilityNameBase + "ServiceA1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2 + "," + bundleName2; + params["targetAbility"] = abilityName2 + "," + abilityName3; + params["type"] = "Service,Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnConnect, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityNumInStack(abilityName3, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbilityCaller, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1700 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1800 + * @tc.name : Visible attribute impact on terminateAbilityResult + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.terminateAbilityResult Service and terminateAbility PageB2 + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1800, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1800 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = 1; + STAbilityUtil::PublishEvent(terminateAbilityResult, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + STAbilityUtil::PublishEvent(terminateAbility, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); + ExpectAbilityNumInStack(abilityName, 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1800 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_1900 + * @tc.name : Visible attribute impact on disconnectService + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.disconnectService Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_1900, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1900 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Service"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnConnect, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = 0; + STAbilityUtil::PublishEvent(disconnectService, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnDisconnect, abilityStateCountOne), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_1900 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2000 + * @tc.name : Visible attribute impact on data Release + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) start a data ability(Data) whose visible attribute is false + * 3.PageB2 has the same bundleName as Data + * 4.Release Data + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2000, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2000 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Data"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "DataRelease"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateInsert, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_DATA); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2000 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2100 + * @tc.name : Visible attribute impact on terminateAbilityCaller + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) Connect a Service ability(Service) whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.terminateCaller Service + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2100 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "Page"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + int eventCode = -1; + STAbilityUtil::PublishEvent(terminateAbilityCaller, eventCode, abilityName); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2100 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2200 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability(PageA1) whose visible attribute is false + * 3.PageA2 has the same bundleName as PageA1 + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2200 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string abilityName2 = abilityNameBase + "PageA1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentPageAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2200 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2300 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability(PageB1) whose visible attribute is false + * 3.PageA2 has the different bundleName as PageB1 + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2300 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB1"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentPageAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2300 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2400 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability(PageB2) whose visible attribute is true + * 3.PageA2 has the different bundleName as PageB2 + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2400 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "PageB2"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentPageAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + + ShowDump(); + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1); + ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2400 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2500 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageA2) whose visible attribute is true + * 2.The ability(PageA2) get the wantagent to starts an ability whose visible attribute is false + * 3.PageA2 has the different bundleName as Service + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2500 start"; + std::string bundleName = bundleNameBase + "PageA"; + std::string abilityName = abilityNameBase + "PageA2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentServiceAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 0, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2500 end"; +} + +/* + * @tc.number : AMS_ABILITY_VISIBLE_2600 + * @tc.name : Visible attribute impact on wantagent + * @tc.desc : 1.The test process starts an ability(PageB2) whose visible attribute is true + * 2.The ability(PageB2) get the wantagent to starts an ability whose visible attribute is false + * 3.PageB2 has the same bundleName as Service + * 4.trigger wantagent + */ +HWTEST_F(AmsAbilityVisibleTest, AMS_ABILITY_VISIBLE_2600, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2600 start"; + std::string bundleName = bundleNameBase + "ServiceB"; + std::string abilityName = abilityNameBase + "PageB2"; + std::string bundleName2 = bundleNameBase + "ServiceB"; + std::string abilityName2 = abilityNameBase + "Service"; + + MAP_STR_STR params; + params["targetBundle"] = bundleName2; + params["targetAbility"] = abilityName2; + params["type"] = "TriggerWantAgentServiceAbility"; + + Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); + STAbilityUtil::StartAbility(want, abilityMs_); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); + int eventCode = 0; + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, triggerWantAgentState, eventCode), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnCommand, abilityStateCountOne), 0); + + ExpectAbilityNumInStack(abilityName, 1); + ExpectAbilityNumInStack(abilityName2, 1, DUMP_SERVICE); + ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); + GTEST_LOG_(INFO) << "AmsAbilityVisibleTest AMS_ABILITY_VISIBLE_2600 end"; +} \ No newline at end of file diff --git a/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn b/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn old mode 100644 new mode 100755 index a305d3cc51b70ab0030d8e2b2c6b57d60ef1dd7c..658d8d9153d97698d54e289c03b1e8b67a42c1e5 --- a/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_app_process_manage_test/BUILD.gn @@ -21,6 +21,7 @@ ohos_systemtest("ams_app_process_manage_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -47,6 +48,7 @@ ohos_systemtest("ams_app_process_manage_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_configuration_updated_test/BUILD.gn b/test/systemtest/common/ams/ams_configuration_updated_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..173f0d0fed868221351c03619570bb2c0c7495e2 --- /dev/null +++ b/test/systemtest/common/ams/ams_configuration_updated_test/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_configuration_updated_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/distributedschedule/safwk/services/safwk/include", + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/system_test_ability_util.cpp", + "ams_configuration_updated_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${appexecfwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_configuration_updated_test" ] +} diff --git a/test/systemtest/common/ams/ams_configuration_updated_test/ams_configuration_updated_test.cpp b/test/systemtest/common/ams/ams_configuration_updated_test/ams_configuration_updated_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..785b81dd6f989d1269a6a3d553f25699e96826b5 --- /dev/null +++ b/test/systemtest/common/ams/ams_configuration_updated_test/ams_configuration_updated_test.cpp @@ -0,0 +1,613 @@ +/* + * Copyright (c) 2021 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 "ability_append_test_info.h" +// #include "ability_lifecycle.h" +// #include "ability_lifecycle_executor.h" +// #include "ability_manager_errors.h" +// #include "ability_manager_service.h" +// #include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +// #include "event.h" +#include "hilog_wrapper.h" +// #include "module_test_dump_util.h" +// #include "sa_mgr_client.h" +// #include "semaphore_ex.h" +// #include "skills.h" +#include "stoperator.h" +// #include "system_ability_definition.h" +#include "system_test_ability_util.h" +// #include "uri.h" +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +// using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; + +using MAP_STR_STR = std::map; +static const string KIT_BUNDLE_NAME = "com.ohos.amsst.ConfigurationUpdated"; +static const string KIT_HAP_NAME = "amsConfigurationUpdatedTest"; +static const string MAIN_ABILITY = "MainAbility"; +static const string SECOND_ABILITY = "SecondAbility"; +static const string THIRD_ABILITY = "ThirdAbility"; +static const string FOURTH_ABILITY = "FourthAbility"; +static const string FIFTH_ABILITY = "FifthAbility"; +static const string SIXTH_ABILITY = "SixthAbility"; +static constexpr int WAIT_TIME = 1; +static constexpr int WAIT_LAUNCHER_TIME = 5; +static constexpr int WAIT_SETUP_TIME = 1; +static constexpr int WAIT_TEARDOWN_TIME = 1; +static string g_eventMessage = ""; +static string g_tempDataStr = ""; + +std::vector eventList = { + g_EVENT_RESP_MAIN_LIFECYCLE, + g_EVENT_RESP_SECOND_LIFECYCLE, + g_EVENT_RESP_THIRD_LIFECYCLE, + g_EVENT_RESP_FOURTH_LIFECYCLE, + g_EVENT_RESP_FIFTH_LIFECYCLE, + g_EVENT_RESP_SIXTH_LIFECYCLE, +}; + +class AmsConfigurationUpdatedTest : public testing::Test { + public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + // static void Reinstall(const std::string &hapName, const std::string &bundleName); + // void ResetSystem() const; + static bool SubscribeEvent(); + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber(){}; + }; + + static sptr g_abilityMs; + static Event event; + static std::shared_ptr subscriber_; + }; + + Event AmsConfigurationUpdatedTest::event = Event(); + sptr AmsConfigurationUpdatedTest::g_abilityMs = nullptr; + std::shared_ptr AmsConfigurationUpdatedTest::subscriber_ = nullptr; + + void AmsConfigurationUpdatedTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) + { + GTEST_LOG_(INFO) << "\nOnReceiveEvent: event====>" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "\nOnReceiveEvent: data=====>" << data.GetData(); + GTEST_LOG_(INFO) << "\nOnReceiveEvent: code=====>" << data.GetCode(); + if (find(eventList.begin(), eventList.end(), data.GetWant().GetAction()) != eventList.end()) { + TestCompleted(event, data.GetData(), data.GetCode()); + } + } + + int AmsConfigurationUpdatedTest::TestWaitCompleted( + Event &event, const std::string &eventName, const int code, const int timeout) + { + GTEST_LOG_(INFO) << "---------->\n\nTestWaitCompleted ====>: " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); + } + + void AmsConfigurationUpdatedTest::TestCompleted(Event &event, const std::string &eventName, const int code) + { + GTEST_LOG_(INFO) << "----------<\nTestCompleted ====>: " << eventName << " " << code << "\n" ; + return STAbilityUtil::Completed(event, eventName, code); + } + + void AmsConfigurationUpdatedTest::SetUpTestCase(void) + { + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "\nSubscribeEvent error====<"; + } + } + + void AmsConfigurationUpdatedTest::TearDownTestCase(void) + { + CommonEventManager::UnSubscribeCommonEvent(subscriber_); + } + + void AmsConfigurationUpdatedTest::SetUp(void) + { + STAbilityUtil::Install(KIT_HAP_NAME); + sleep(WAIT_SETUP_TIME); + STAbilityUtil::CleanMsg(event); + } + + void AmsConfigurationUpdatedTest::TearDown(void) + { + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME); + sleep(WAIT_TEARDOWN_TIME); + STAbilityUtil::CleanMsg(event); + } + + bool AmsConfigurationUpdatedTest::SubscribeEvent() + { + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber_); + } + + /** + * @tc.number : 0100 + * @tc.name : AMS_UpdateConfiguration_0100 + * @tc.desc : Verify whether the results of the orientation function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0100, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("orientation"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_EQ(TestWaitCompleted(event, "UpdatedUpdated", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0100 end=========<"; + } + + /** + * @tc.number : 0200 + * @tc.name : AMS_UpdateConfiguration_0200 + * @tc.desc : Verify whether the results of the orientation, locale function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0200, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SECOND_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("locale"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_EQ(TestWaitCompleted(event, "UpdatedUpdated", SECOND_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0200 end=========<"; + } + + /** + * @tc.number : 0300 + * @tc.name : AMS_UpdateConfiguration_0300 + * @tc.desc : Verify whether the results of the orientation, locale, layout function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0300, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", THIRD_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + g_abilityMs = nullptr; + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", THIRD_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("layout"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_EQ(TestWaitCompleted(event, "UpdatedUpdated", THIRD_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0300 end=========<"; + } + + /** + * @tc.number : 0400 + * @tc.name : AMS_UpdateConfiguration_0400 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0400, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FOURTH_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", FOURTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("density#fontSize#"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_EQ(TestWaitCompleted(event, "UpdatedUpdated", FOURTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0400 end=========<"; + } + + /** + * @tc.number : 0500 + * @tc.name : AMS_UpdateConfiguration_0500 + * @tc.desc : Verify whether the results of the orientation, locale, layout,fontSize,density function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0500, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", FIFTH_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", FIFTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("fontSize#density"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_EQ(TestWaitCompleted(event, "UpdatedUpdated", FIFTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0500 end=========<"; + } + + + /** + * @tc.number : 0600 + * @tc.name : AMS_UpdateConfiguration_0600 + * @tc.desc : Verify whether the results of the orientation function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0600, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("locale#layout#fontSize#density"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "OnInactiveOnBackgroundOnStop"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnStop", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_NE(TestWaitCompleted(event, "UpdatedUpdated", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0600 end=========<"; + } + + /** + * @tc.number : 0700 + * @tc.name : AMS_UpdateConfiguration_0700 + * @tc.desc : Verify whether the results of the orientation, locale function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0700, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SECOND_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("layout#fontSize#density"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "OnInactiveOnBackgroundOnStop"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnStop", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SECOND_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_NE(TestWaitCompleted(event, "UpdatedUpdated", SECOND_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0700 end=========<"; + } + + /** + * @tc.number : 0800 + * @tc.name : AMS_UpdateConfiguration_0800 + * @tc.desc : Verify whether the results of the function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0800, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SIXTH_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("orientation"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "OnInactiveOnBackgroundOnStop"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnStop", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + g_tempDataStr = "OnConfigurationUpdated"; + EXPECT_NE(TestWaitCompleted(event, "OnConfigurationUpdated", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0800 end=========<"; + } + + + /** + * @tc.number : 0900 + * @tc.name : AMS_UpdateConfiguration_0900 + * @tc.desc : Verify whether the results of the function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_0900, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SIXTH_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("orientation#locale"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "OnInactiveOnBackgroundOnStop"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnStop", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + g_tempDataStr = "OnConfigurationUpdated"; + EXPECT_NE(TestWaitCompleted(event, "OnConfigurationUpdated", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_0900 end=========<"; + } + + + /** + * @tc.number : 1000 + * @tc.name : AMS_UpdateConfiguration_1000 + * @tc.desc : Verify whether the results of the function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_1000, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SIXTH_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("orientation#locale#layout"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "OnInactiveOnBackgroundOnStop"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnStop", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + g_tempDataStr = "OnConfigurationUpdated"; + EXPECT_NE(TestWaitCompleted(event, "OnConfigurationUpdated", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1000 end=========<"; + } + + /** + * @tc.number : 1100 + * @tc.name : AMS_UpdateConfiguration_1100 + * @tc.desc : Verify whether the results of the function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_1100, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SIXTH_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("orientation#locale#layout#fontSize"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "OnInactiveOnBackgroundOnStop"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnStop", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + g_tempDataStr = "OnConfigurationUpdated"; + EXPECT_NE(TestWaitCompleted(event, "OnConfigurationUpdated", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1100 end=========<"; + } + + /** + * @tc.number : 1200 + * @tc.name : AMS_UpdateConfiguration_1200 + * @tc.desc : Verify whether the results of the function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_1200, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", SIXTH_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + DummyConfiguration mDummyConfiguration("orientation#locale#layout#fontSize#density"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "OnInactiveOnBackgroundOnStop"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnStop", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", SIXTH_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + g_tempDataStr = "OnConfigurationUpdated"; + EXPECT_NE(TestWaitCompleted(event, "OnConfigurationUpdated", SIXTH_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1200 end=========<"; + } + + /** + * @tc.number : 1300 + * @tc.name : AMS_UpdateConfiguration_1300 + * @tc.desc : Verify whether the results of the orientation function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_1300, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE, WAIT_LAUNCHER_TIME), 0); + + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, g_abilityMs); + GTEST_LOG_(INFO) << "====>Want::FLAG_HOME_INTENT_FROM_SYSTEM"; + DummyConfiguration mDummyConfiguration("orientation"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + + want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility S ====>> " << eCode; + + g_tempDataStr = "OnInactiveOnBackgroundOnForegroundOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnInactiveOnBackgroundOnForegroundOnActive", MAIN_ABILITY_CODE), 0); + + g_tempDataStr = "Updated"; + EXPECT_EQ(TestWaitCompleted(event, "Updated", MAIN_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1300 end=========<"; + } + /** + * @tc.number : 1400 + * @tc.name : AMS_UpdateConfiguration_1400 + * @tc.desc : Verify whether the results of the orientation function of the system configuration concerned by capability are correct. + */ + + HWTEST_F(AmsConfigurationUpdatedTest, AMS_UpdateConfiguration_1400, Function | MediumTest | Level1) + { + GTEST_LOG_(INFO) << "==========>\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << "\nStartAbility ====>> " << eCode; + + g_tempDataStr = "OnStartOnActive"; + EXPECT_EQ(TestWaitCompleted(event, "OnStartOnActive", MAIN_ABILITY_CODE), 0); + + DummyConfiguration mDummyConfiguration("orientation#locale"); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + g_abilityMs->UpdateConfiguration(mDummyConfiguration); + + g_tempDataStr = "UpdatedUpdated"; + EXPECT_EQ(TestWaitCompleted(event, "UpdatedUpdated", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "\nAmsConfigurationUpdatedTest AMS_UpdateConfiguration_1400 end=========<"; + } + +} // namespace + diff --git a/test/systemtest/common/ams/ams_data_ability_test/BUILD.gn b/test/systemtest/common/ams/ams_data_ability_test/BUILD.gn old mode 100644 new mode 100755 index 1688797f5ea89dfe8170940e25b772315ab27fe9..c3b3641afa23a07e3ce259f65311f22ec6d35c0a --- a/test/systemtest/common/ams/ams_data_ability_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_data_ability_test/BUILD.gn @@ -22,6 +22,7 @@ ohos_systemtest("ams_data_ability_test") { include_dirs = [ "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -50,6 +51,7 @@ ohos_systemtest("ams_data_ability_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_dfx_test/BUILD.gn b/test/systemtest/common/ams/ams_dfx_test/BUILD.gn old mode 100644 new mode 100755 index 15748cce11f5fccbd6840830bdb772bcc2742816..8d4f04ed0a87e3021e1f8309dbd589e11f87e4c5 --- a/test/systemtest/common/ams/ams_dfx_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_dfx_test/BUILD.gn @@ -21,6 +21,7 @@ ohos_systemtest("ams_dfx_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -47,6 +48,7 @@ ohos_systemtest("ams_dfx_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_dfx_test/ams_dfx_test.cpp b/test/systemtest/common/ams/ams_dfx_test/ams_dfx_test.cpp index 64cba34fe8aee241291d8a6304b4787bb16aacae..c52314ce5049280b4e9c01937d7775a9b9e9a64b 100644 --- a/test/systemtest/common/ams/ams_dfx_test/ams_dfx_test.cpp +++ b/test/systemtest/common/ams/ams_dfx_test/ams_dfx_test.cpp @@ -66,9 +66,9 @@ static const std::string abilityStateOnInactive = ":OnInactive"; static const std::string abilityStateOnBackground = ":OnBackground"; static const std::string abilityStateOnForeground = ":OnForeground"; static const std::string abilityStateOnNewWant = ":OnNewWant"; -static const std::string g_abilityStateOnCommand = ":OnCommand"; -static const std::string g_abilityStateOnConnect = ":OnConnect"; -static const std::string g_abilityStateOnDisconnect = ":OnDisconnect"; +static const std::string abilityStateOnCommand = ":OnCommand"; +static const std::string abilityStateOnConnect = ":OnConnect"; +static const std::string abilityStateOnDisconnect = ":OnDisconnect"; static const int abilityStateCountOne = 1; static const int abilityStateCountTwo = 2; enum AbilityState_Test { @@ -114,9 +114,6 @@ public: const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = (DUMP_STACK + " 1")); void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum); void ExpectServiceAbilityNumInStack(const std::string &abilityName, int abilityNum); - void GetFreeMem(const std::string &cmd, std::string &result); - std::string RemoveSurplusSpaces(const std::string &src); - std::vector Split(std::string str, const std::string &delim); class AppEventSubscriber : public CommonEventSubscriber { public: explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) @@ -167,13 +164,11 @@ public: static sptr abilityMs_; static STtools::Event event_; static std::shared_ptr subscriber_; - static int *memTestValue_; }; sptr AmsDFXTest::appMs_ = nullptr; sptr AmsDFXTest::abilityMs_ = nullptr; STtools::Event AmsDFXTest::event_ = STtools::Event(); -int *AmsDFXTest::memTestValue_ = nullptr; std::shared_ptr AmsDFXTest::subscriber_ = nullptr; size_t AmsDFXTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; int AmsDFXTest::AbilityConnectCallback::resultConnectCode = 0; @@ -209,9 +204,6 @@ void AmsDFXTest::SetUp(void) void AmsDFXTest::TearDown(void) { GTEST_LOG_(INFO) << "void AmsDFXTest::TearDown(void)"; - if (memTestValue_) { - delete[] memTestValue_; - } std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); STAbilityUtil::UninstallBundle(bundleNames); @@ -263,6 +255,10 @@ void AmsDFXTest::CheckAbilityStateByName(const std::string &abilityName, const s EXPECT_NE(pos, result.end()); MTDumpUtil::GetInstance()->GetAll("State", info, result); EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } // ability state if (midState != "") { bool compareResult = ((*pos == state) || (*pos == midState)); @@ -330,53 +326,6 @@ void AmsDFXTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) } } -void AmsDFXTest::GetFreeMem(const std::string &cmd, std::string &result) -{ - result.clear(); - int MAX_SIZE = 1024; - char buf_ps[MAX_SIZE]; - FILE *ptr; - string command = "free " + cmd + "| grep Mem:"; - if (!command.empty() && (ptr = popen(command.c_str(), "r")) != nullptr) { - while (fgets(buf_ps, MAX_SIZE, ptr) != nullptr) { - result.append(buf_ps); - } - pclose(ptr); - ptr = nullptr; - } -} - -std::string AmsDFXTest::RemoveSurplusSpaces(const std::string &src) -{ - std::string result = ""; - for (int i = 0; src[i] != '\0'; i++) { - if (src[i] != ' ') - result.append(1, src[i]); - else if (src[i + 1] != ' ') - result.append(1, src[i]); - } - return result; -} - -std::vector AmsDFXTest::Split(std::string str, const std::string &delim) -{ - std::vector splitString; - while (str.size()) { - size_t index = str.find(delim); - if (index != std::string::npos) { - splitString.push_back(str.substr(0, index)); - str = str.substr(index + delim.size()); - if (str.size() == 0) { - splitString.push_back(str); - } - } else { - splitString.push_back(str); - str = ""; - } - } - return splitString; -} - /* * @tc.number : AMS_DFX_0100 * @tc.name : Lifecycle switch timeout. @@ -645,7 +594,7 @@ HWTEST_F(AmsDFXTest, AMS_DFX_1000, TestSize.Level1) { GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_1000 start"; std::string bundleName = bundleNameBase + "DFX"; - std::string abilityName = abilityNameBase + "DFXA1"; + std::string abilityName = "AmsDfxStServiceAbilityA1"; MAP_STR_STR params; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); @@ -679,7 +628,7 @@ HWTEST_F(AmsDFXTest, AMS_DFX_1100, TestSize.Level1) { GTEST_LOG_(INFO) << "AmsDFXTest AMS_DFX_1100 start"; std::string bundleName = bundleNameBase + "DFX"; - std::string abilityName = abilityNameBase + "DFXA2"; + std::string abilityName = "AmsDfxStServiceAbilityA2"; MAP_STR_STR params; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); diff --git a/test/systemtest/common/ams/ams_kit_test/BUILD.gn b/test/systemtest/common/ams/ams_kit_test/BUILD.gn old mode 100644 new mode 100755 index 0758fd398b5c128d58b3b20275005bdf73608b9d..9a3ebe55097f18445962a3fe814fb8f02ffb2d92 --- a/test/systemtest/common/ams/ams_kit_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_kit_test/BUILD.gn @@ -22,6 +22,7 @@ ohos_systemtest("ams_kit_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -46,6 +47,7 @@ ohos_systemtest("ams_kit_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ @@ -63,6 +65,7 @@ ohos_systemtest("ams_kit_service_ability_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -87,6 +90,7 @@ ohos_systemtest("ams_kit_service_ability_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ @@ -104,6 +108,7 @@ ohos_systemtest("ams_kit_data_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -131,6 +136,7 @@ ohos_systemtest("ams_kit_data_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ @@ -149,6 +155,7 @@ ohos_systemtest("ams_kit_a_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -174,6 +181,7 @@ ohos_systemtest("ams_kit_a_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ @@ -192,6 +200,7 @@ ohos_systemtest("ams_kit_want_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -216,6 +225,7 @@ ohos_systemtest("ams_kit_want_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ @@ -234,6 +244,7 @@ ohos_systemtest("ams_kit_skills_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -258,6 +269,7 @@ ohos_systemtest("ams_kit_skills_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ @@ -276,6 +288,7 @@ ohos_systemtest("ams_kit_lifecycle_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -300,6 +313,7 @@ ohos_systemtest("ams_kit_lifecycle_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ @@ -318,6 +332,7 @@ ohos_systemtest("ams_kit_processinfo_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", + "//third_party/jsoncpp/include", ] sources = [ "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", @@ -342,6 +357,7 @@ ohos_systemtest("ams_kit_processinfo_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ diff --git a/test/systemtest/common/ams/ams_missionstack_test/BUILD.gn b/test/systemtest/common/ams/ams_missionstack_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3b493d5a5532b4f902d1c395b73f466b18e523a8 --- /dev/null +++ b/test/systemtest/common/ams/ams_missionstack_test/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") + +module_output_path = "appexecfwk_standard/ams" + +ohos_systemtest("ams_missionstack_test") { + module_out_path = module_output_path + + include_dirs = [ + "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common/", + "//foundation/distributedschedule/safwk/services/safwk/include", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + ] + + sources = [ + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/event.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/module_test_dump_util.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/stoperator.cpp", + "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/src/system_test_ability_util.cpp", + "ams_missionstack_test.cpp", + ] + + configs = [ + "${aafwk_path}/services/abilitymgr:abilityms_config", + "${appexecfwk_path}/services/appmgr:appmgr_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:dummy_classes", + "${aafwk_path}/interfaces/innerkits/want:want", + "${aafwk_path}/services/abilitymgr:abilityms", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":ams_missionstack_test" ] +} diff --git a/test/systemtest/common/ams/ams_missionstack_test/ams_missionstack_test.cpp b/test/systemtest/common/ams/ams_missionstack_test/ams_missionstack_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ffac8ca8162d73d13cb1f960fa02440008ed675 --- /dev/null +++ b/test/systemtest/common/ams/ams_missionstack_test/ams_missionstack_test.cpp @@ -0,0 +1,850 @@ +/* + * Copyright (c) 2021 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 "ability_append_test_info.h" +// #include "ability_lifecycle.h" +// #include "ability_lifecycle_executor.h" +// #include "ability_manager_errors.h" +// #include "ability_manager_service.h" +// #include "app_mgr_service.h" +#include "common_event.h" +#include "common_event_manager.h" +//#include "event.h" +#include "hilog_wrapper.h" +// #include "module_test_dump_util.h" +// #include "sa_mgr_client.h" +// #include "semaphore_ex.h" +// #include "skills.h" +#include "stoperator.h" +//#include "system_ability_definition.h" +#include "system_test_ability_util.h" +//#include "uri.h" +namespace { +using namespace OHOS; +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +//using namespace OHOS::MTUtil; +using namespace OHOS::STtools; +using namespace OHOS::STABUtil; +using namespace testing::ext; + +using MAP_STR_STR = std::map; +static const string KIT_BUNDLE_NAME = "com.ohos.amsst.MissionStack"; +static const string KIT_HAP_NAME = "amsMissionStackTest"; +static const string KIT_BUNDLE_NAME_SUBSIDIARY = "com.ohos.amsst.MissionStackSubsidiary"; +static const string KIT_HAP_NAME_SUBSIDIARY = "amsMissionStackTestSubsidiary"; +static const string MAIN_ABILITY_NAME = "MainAbility"; +static const string SECOND_ABILITY_NAME = "SecondAbility"; +static const string THIRD_ABILITY_NAME = "ThirdAbility"; +static constexpr int WAIT_TIME = 1; +static constexpr int WAIT_LAUNCHER_TIME = 5; + + +static string g_eventMessage = ""; +class AmsMissionStackTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + static void Reinstall(const std::string &hapName, const std::string &bundleName); + void ResetSystem() const; + static bool SubscribeEvent(); + static int TestWaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 10); + static void TestCompleted(Event &event, const std::string &eventName, const int code); + + class AppEventSubscriber : public CommonEventSubscriber { + public: + explicit AppEventSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; + virtual void OnReceiveEvent(const CommonEventData &data) override; + ~AppEventSubscriber(){}; + }; + + static sptr g_abilityMs; + static Event event; +}; + +Event AmsMissionStackTest::event = Event(); +sptr AmsMissionStackTest::g_abilityMs = nullptr; + +void AmsMissionStackTest::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + GTEST_LOG_(INFO) << "OnReceiveEvent: event=" << data.GetWant().GetAction(); + GTEST_LOG_(INFO) << "OnReceiveEvent: data=" << data.GetData(); + GTEST_LOG_(INFO) << "OnReceiveEvent: code=" << data.GetCode(); + if (data.GetWant().GetAction() == g_EVENT_RESP_MAIN_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_THIRD_LIFECYCLE || + data.GetWant().GetAction() == g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY + ) { + TestCompleted(event, data.GetData(), data.GetCode()); + } else if (data.GetWant().GetAction() == g_EVENT_RESP_MAIN || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND || + data.GetWant().GetAction() == g_EVENT_RESP_THIRD || + data.GetWant().GetAction() == g_EVENT_RESP_MAIN_SUBSIDIARY || + data.GetWant().GetAction() == g_EVENT_RESP_SECOND_SUBSIDIARY + ) { + g_eventMessage = data.GetData(); + TestCompleted(event, data.GetWant().GetAction(), data.GetCode()); + GTEST_LOG_(INFO) << "OnReceiveEvent: g_eventMessage=" << data.GetData(); + } +} + +int AmsMissionStackTest::TestWaitCompleted( + Event &event, const std::string &eventName, const int code, const int timeout) +{ + GTEST_LOG_(INFO) << "TestWaitCompleted : " << eventName << " " << code; + return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); +} + +void AmsMissionStackTest::TestCompleted(Event &event, const std::string &eventName, const int code) +{ + GTEST_LOG_(INFO) << "TestCompleted : " << eventName << " " << code; + return STAbilityUtil::Completed(event, eventName, code); +} + +void AmsMissionStackTest::SetUpTestCase(void) +{ + if (!SubscribeEvent()) { + GTEST_LOG_(INFO) << "SubscribeEvent error"; + } +} + +void AmsMissionStackTest::TearDownTestCase(void) +{} + +static int CODE_ = 0; +void AmsMissionStackTest::SetUp(void) +{ + STAbilityUtil::Install(KIT_HAP_NAME); + STAbilityUtil::CleanMsg(event); + CODE_++; + sleep(WAIT_LAUNCHER_TIME); +} + +void AmsMissionStackTest::TearDown(void) +{ + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME); + STAbilityUtil::CleanMsg(event); +} + +bool AmsMissionStackTest::SubscribeEvent() +{ + std::vector eventList = { + g_EVENT_RESP_MAIN_LIFECYCLE, + g_EVENT_RESP_SECOND_LIFECYCLE, + g_EVENT_RESP_THIRD_LIFECYCLE, + g_EVENT_RESP_MAIN, + g_EVENT_RESP_SECOND, + g_EVENT_RESP_THIRD, + + g_EVENT_RESP_MAIN_SUBSIDIARY, + g_EVENT_RESP_MAIN_LIFECYCLE_SUBSIDIARY, + + g_EVENT_RESP_SECOND_SUBSIDIARY, + g_EVENT_RESP_SECOND_LIFECYCLE_SUBSIDIARY, + }; + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + auto subscriber = std::make_shared(subscribeInfo); + return CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void AmsMissionStackTest::Reinstall(const std::string &hapName, const std::string &bundleName) +{ + STAbilityUtil::Uninstall(bundleName); + STAbilityUtil::Install(hapName); +} + + +/** + * @tc.number : FWK_MissionStack_0100 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0100 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnStop", SECOND_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0100 end"; +} + +/** + * @tc.number : FWK_MissionStack_0200 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + EXPECT_NE(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0200 end"; +} + +/** + * @tc.number : FWK_MissionStack_0300 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, g_abilityMs); + + EXPECT_NE(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0300 end"; +} + +/** + * @tc.number : FWK_MissionStack_0400 + * @tc.name : + * @tc.desc : + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0400 start"; + //GTEST_LOG_(INFO) << "需要使用JS环境测试"; + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0400 end"; +} + +/** + * @tc.number : FWK_MissionStack_0500 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start third ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", THIRD_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", THIRD_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_THIRD, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_4"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_THIRD, CODE_), 0); + + EXPECT_NE(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0500 end"; +} + +/** + * @tc.number : FWK_MissionStack_0600 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start third ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_5"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + EXPECT_NE(TestWaitCompleted(event, "OnStart", THIRD_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0600 end"; +} + +/** + * @tc.number : FWK_MissionStack_0700 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_6"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, g_abilityMs); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0700 end"; +} + +/** + * @tc.number : FWK_MissionStack_0800 + * @tc.name : + * @tc.desc : + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0800 start"; + //GTEST_LOG_(INFO) << "需要使用JS环境测试"; + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0800 end"; +} + +/** + * @tc.number : FWK_MissionStack_0900 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_0900, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0900 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_8"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_8"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnStop", SECOND_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_0900 end"; +} + +/** + * @tc.number : FWK_MissionStack_1000 + * @tc.name : test LockMission in ability_context.h + * @tc.desc : Verify that the result of LockMission function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1000 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_9"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + string appInfo = g_eventMessage; + + GTEST_LOG_(INFO) << "id=" << appInfo; + //EXPECT_EQ(appInfo, "1"); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1000 end"; +} + +/** + * @tc.number : FWK_MissionStack_1100 + * @tc.name : + * @tc.desc : + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1100 start"; + //GTEST_LOG_(INFO) << "需要使用JS环境测试"; + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1100 end"; +} + +/** + * @tc.number : FWK_MissionStack_1200 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1200 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_11"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1200 end"; +} + +/** + * @tc.number : FWK_MissionStack_1300 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1300 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_12"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1300 end"; +} + +/** + * @tc.number : FWK_MissionStack_1400 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1400 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_13"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_13"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1400 end"; +} + +/** + * @tc.number : FWK_MissionStack_1500 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1500 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_14"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_SECOND, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_14"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); + EXPECT_NE(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1500 end"; +} + +/** + * @tc.number : FWK_MissionStack_1600 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1600 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, g_abilityMs); + sleep(WAIT_LAUNCHER_TIME); + STAbilityUtil::CleanMsg(event); + + STAbilityUtil::Install(KIT_HAP_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + sleep(WAIT_LAUNCHER_TIME); + want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME_SUBSIDIARY, params); + // start first ability + eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) <<"SUBSIDIARY:StartAbility:eCode=" << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN_SUBSIDIARY, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE_SUBSIDIARY,WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN_SUBSIDIARY, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_1"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE_SUBSIDIARY,WAIT_LAUNCHER_TIME), 0); + + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1600 end"; +} + +// /** +// * @tc.number : FWK_MissionStack_1700 +// * @tc.name : test MoveMissionToEnd in ability_context.h +// * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. +// */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1700 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + STAbilityUtil::StartAbility(wantEntity, g_abilityMs); + sleep(WAIT_LAUNCHER_TIME); + STAbilityUtil::CleanMsg(event); + + STAbilityUtil::Install(KIT_HAP_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + sleep(WAIT_LAUNCHER_TIME); + want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME_SUBSIDIARY, params); + // start first ability + eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) <<"SUBSIDIARY:StartAbility:eCode=" << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN_SUBSIDIARY, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_0"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE_SUBSIDIARY,WAIT_LAUNCHER_TIME), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE_SUBSIDIARY), 0); + + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN_SUBSIDIARY, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_2"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN_SUBSIDIARY, CODE_), 0); + EXPECT_NE(TestWaitCompleted(event, "OnBackground", SECOND_ABILITY_CODE_SUBSIDIARY,WAIT_LAUNCHER_TIME), 0); + + STAbilityUtil::Uninstall(KIT_BUNDLE_NAME_SUBSIDIARY); + STAbilityUtil::CleanMsg(event); + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1700 end"; +} + +/** + * @tc.number : FWK_MissionStack_1800 + * @tc.name : test MoveMissionToEnd in ability_context.h + * @tc.desc : Verify that the result of MoveMissionToEnd function is correct. + */ +HWTEST_F(AmsMissionStackTest, FWK_MissionStack_1800, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1800 start"; + MAP_STR_STR params; + Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); + // start first ability + ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); + GTEST_LOG_(INFO) << eCode; + + EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); + EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + STAbilityUtil::CleanMsg(event); + STAbilityUtil::PublishEvent( + g_EVENT_REQU_MAIN, CODE_, "MissionStack_" + std::to_string((int)MissionStackApi::LockMission) + "_17"); + EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + + EXPECT_NE(TestWaitCompleted(event, "OnBackground", MAIN_ABILITY_CODE,WAIT_LAUNCHER_TIME), 0); + + GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_MissionStack_1800 end"; +} + +// /** +// * @tc.number : FWK_SaveAbilityState_0100 +// * @tc.name : +// * @tc.desc : +// */ +// HWTEST_F(AmsMissionStackTest, FWK_SaveAbilityState_0100, Function | MediumTest | Level1) +// { +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_SaveAbilityState_0100 start"; +// MAP_STR_STR params; +// Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); +// // start first ability +// ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); +// GTEST_LOG_(INFO) << eCode; + +// EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); +// EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); + +// Want wantEntity; +// wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); +// STAbilityUtil::StartAbility(wantEntity, g_abilityMs); + +// EXPECT_NE(TestWaitCompleted(event, "OnSaveAbilityState", MAIN_ABILITY_CODE), 0); +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_SaveAbilityState_0100 end"; +// } + +// /** +// * @tc.number : FWK_SaveAbilityState_0200 +// * @tc.name : +// * @tc.desc : +// */ +// HWTEST_F(AmsMissionStackTest, FWK_SaveAbilityState_0200, Function | MediumTest | Level1) +// { +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_SaveAbilityState_0200 start"; + +// // 该case需要屏幕翻转事件 +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_SaveAbilityState_0200 end"; +// } + +// /** +// * @tc.number : FWK_SaveAbilityState_0300 +// * @tc.name : +// * @tc.desc : +// */ +// HWTEST_F(AmsMissionStackTest, FWK_SaveAbilityState_0300, Function | MediumTest | Level1) +// { +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_SaveAbilityState_0300 start"; +// MAP_STR_STR params; +// Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); +// // start first ability +// ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); +// GTEST_LOG_(INFO) << eCode; + +// EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); +// EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); +// STAbilityUtil::CleanMsg(event); +// STAbilityUtil::PublishEvent( +// g_EVENT_REQU_MAIN, CODE_, "AbilityState_" + std::to_string((int)TestAbilityState::OnSaveAbilityState) + "_2"); +// EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + +// EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); +// EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); + +// EXPECT_NE(TestWaitCompleted(event, "OnSaveAbilityState", MAIN_ABILITY_CODE), 0); +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_SaveAbilityState_0300 end"; +// } + +// /** +// * @tc.number : FWK_RestoreAbilityState_0100 +// * @tc.name : +// * @tc.desc : +// */ +// HWTEST_F(AmsMissionStackTest, FWK_RestoreAbilityState_0100, Function | MediumTest | Level1) +// { +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_RestoreAbilityState_0100 start"; + +// MAP_STR_STR params; +// Want want = STAbilityUtil::MakeWant("device", THIRD_ABILITY_NAME, KIT_BUNDLE_NAME, params); +// // start first ability +// ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); +// GTEST_LOG_(INFO) << eCode; + +// EXPECT_EQ(TestWaitCompleted(event, "OnStart", THIRD_ABILITY_CODE), 0); +// EXPECT_EQ(TestWaitCompleted(event, "OnActive", THIRD_ABILITY_CODE), 0); + +// Want wantEntity; +// wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); +// STAbilityUtil::StartAbility(wantEntity, g_abilityMs); + +// sleep(WAIT_LAUNCHER_TIME); +// eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); +// GTEST_LOG_(INFO) << eCode; +// EXPECT_EQ(TestWaitCompleted(event, "OnActive", THIRD_ABILITY_CODE), 0); + +// EXPECT_NE(TestWaitCompleted(event, "OnRestoreAbilityState", THIRD_ABILITY_CODE), 0); + +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_RestoreAbilityState_0100 end"; +// } + +// /** +// * @tc.number : FWK_RestoreAbilityState_0200 +// * @tc.name : +// * @tc.desc : +// */ +// HWTEST_F(AmsMissionStackTest, FWK_RestoreAbilityState_0200, Function | MediumTest | Level1) +// { +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_RestoreAbilityState_0200 start"; +// // 该case需要屏幕翻转事件 +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_RestoreAbilityState_0200 end"; +// } + +// /** +// * @tc.number : FWK_RestoreAbilityState_0300 +// * @tc.name : +// * @tc.desc : +// */ +// HWTEST_F(AmsMissionStackTest, FWK_RestoreAbilityState_0300, Function | MediumTest | Level1) +// { +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_RestoreAbilityState_0300 start"; +// MAP_STR_STR params; +// Want want = STAbilityUtil::MakeWant("device", MAIN_ABILITY_NAME, KIT_BUNDLE_NAME, params); +// // start first ability +// ErrCode eCode = STAbilityUtil::StartAbility(want, g_abilityMs, WAIT_TIME); +// GTEST_LOG_(INFO) << eCode; + +// EXPECT_EQ(TestWaitCompleted(event, "OnStart", MAIN_ABILITY_CODE), 0); +// EXPECT_EQ(TestWaitCompleted(event, "OnActive", MAIN_ABILITY_CODE), 0); +// STAbilityUtil::CleanMsg(event); +// STAbilityUtil::PublishEvent( +// g_EVENT_REQU_MAIN, CODE_, "AbilityState_" + std::to_string((int)TestAbilityState::OnRestoreAbilityState) + "_2"); +// EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_MAIN, CODE_), 0); + +// EXPECT_EQ(TestWaitCompleted(event, "OnStart", SECOND_ABILITY_CODE), 0); +// EXPECT_EQ(TestWaitCompleted(event, "OnActive", SECOND_ABILITY_CODE), 0); +// STAbilityUtil::PublishEvent( +// g_EVENT_REQU_SECOND, CODE_, "AbilityState_" + std::to_string((int)TestAbilityState::OnRestoreAbilityState) + "_2"); +// EXPECT_EQ(TestWaitCompleted(event, g_EVENT_RESP_SECOND, CODE_), 0); +// EXPECT_EQ(TestWaitCompleted(event, "OnStop", SECOND_ABILITY_CODE), 0); + +// EXPECT_NE(TestWaitCompleted(event, "OnRestoreAbilityState", MAIN_ABILITY_CODE), 0); + +// GTEST_LOG_(INFO) << "AmsMissionStackTest FWK_RestoreAbilityState_0300 end"; +// } + +} // namespace diff --git a/test/systemtest/common/ams/ams_page_ability_test/BUILD.gn b/test/systemtest/common/ams/ams_page_ability_test/BUILD.gn old mode 100644 new mode 100755 index b5db3c8266353bf84ff7e5aee5b5d671597cb1f8..17487b999aebbec2bf1c572c1ac537f60feb86b4 --- a/test/systemtest/common/ams/ams_page_ability_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_page_ability_test/BUILD.gn @@ -20,6 +20,7 @@ ohos_systemtest("ams_page_ability_test") { include_dirs = [ "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -46,6 +47,7 @@ ohos_systemtest("ams_page_ability_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_page_ability_test/ams_page_ability_test.cpp b/test/systemtest/common/ams/ams_page_ability_test/ams_page_ability_test.cpp index d4f7ea3be81427212ffa2c9b610c1859f3665edd..74be16d8802d2efa153d2fa2dc344458dc2d65eb 100644 --- a/test/systemtest/common/ams/ams_page_ability_test/ams_page_ability_test.cpp +++ b/test/systemtest/common/ams/ams_page_ability_test/ams_page_ability_test.cpp @@ -97,7 +97,6 @@ static const std::string abilityStateOnForeground = ":OnForeground"; static const std::string abilityStateOnNewWant = ":OnNewWant"; static const int abilityStateCountOne = 1; static const int abilityStateCountTwo = 2; -static const int abilityStateCountThree = 3; } // namespace class AmsPageAbilityTest : public testing::Test { @@ -111,7 +110,7 @@ public: static void CheckAbilityStateByName(const std::string &abilityName, const std::vector &info, const std::string &state, const std::string &midState); void ExpectAbilityCurrentState(const std::string &abilityName, const AbilityState_Test ¤tState, - const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = (DUMP_STACK + " 1")); + const AbilityState_Test &midState = AbilityState_Test::ALLSUM, const std::string &args = DUMP_ALL); void ExpectAbilityNumInStack(const std::string &abilityName, int abilityNum); void ClearSystem(); void ShowDump(); @@ -206,6 +205,10 @@ void AmsPageAbilityTest::CheckAbilityStateByName(const std::string &abilityName, EXPECT_NE(pos, result.end()); MTDumpUtil::GetInstance()->GetAll("State", info, result); EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } // ability state if (midState != "") { bool compareResult = ((*pos == state) || (*pos == midState)); @@ -1163,12 +1166,13 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2200, Function | MediumTest | Leve std::string bundleName = bundleNameBase + "A"; std::string abilityName = abilityNameBase + "A1"; MAP_STR_STR params; - params["shouldReturn"] = abilityName; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); @@ -1198,7 +1202,6 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2300, Function | MediumTest | Leve MAP_STR_STR params; params["targetBundle"] = bundleName; params["targetAbility"] = abilityName2; - params["shouldReturn"] = abilityName2; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); @@ -1206,6 +1209,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2300, Function | MediumTest | Leve EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); @@ -1239,7 +1244,6 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2400, Function | MediumTest | Leve MAP_STR_STR params; params["targetBundle"] = bundleName2; params["targetAbility"] = abilityName2; - params["shouldReturn"] = abilityName2; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); @@ -1247,6 +1251,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2400, Function | MediumTest | Leve EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); @@ -1279,16 +1285,17 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2500, Function | MediumTest | Leve MAP_STR_STR params; params["targetBundle"] = bundleName; params["targetAbility"] = abilityName2; - params["shouldReturn"] = abilityName; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); - EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); // ability "A1" not in stack(terminated) ExpectAbilityNumInStack(abilityName, 0); @@ -1413,9 +1420,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2700, Function | MediumTest | Leve EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnBackground, abilityStateCountOne), 0); // Back Ability I4(singletop) - params["shouldReturn"] = abilityName4; - want = STAbilityUtil::MakeWant("device", abilityName4, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName4); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName4 + abilityStateOnStop, abilityStateCountOne), 0); @@ -1424,9 +1430,7 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2700, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); ExpectAbilityCurrentState(abilityName3, AbilityState_Test::BACKGROUND, AbilityState_Test::ACTIVATING); // Back Ability I2(singletop) - params["shouldReturn"] = abilityName2; - want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); @@ -1435,9 +1439,7 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2700, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); ExpectAbilityCurrentState(abilityName3, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); // Back Ability I1(singletop) - params["shouldReturn"] = abilityName1; - want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); ExpectAbilityCurrentState(launcherAbilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); @@ -1577,9 +1579,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_2900, Function | MediumTest | Leve ExpectAbilityNumInStack(abilityName3, 1); ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); // Start Ability I3(SI) Back - params["shouldReturn"] = abilityName3; - want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); @@ -1728,20 +1729,16 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3100, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName3, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); // I3(SI) back - params["shouldReturn"] = abilityName3; - want = STAbilityUtil::MakeWant("device", abilityName3, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountTwo), 0); // Ability I3 back, B1(singletop) State Is ACTIVE ExpectAbilityCurrentState(abilityName5, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); // B1(singletop) back - params["shouldReturn"] = abilityName5; - want = STAbilityUtil::MakeWant("device", abilityName5, bundleName2, params); - STAbilityUtil::StartAbility(want, abilityMs_); + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName5); - EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnActive, abilityStateCountThree), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnBackground, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnStop, abilityStateCountOne), 0); @@ -1955,9 +1952,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3700, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); // Back Ability G2(singletop) - params["shouldReturn"] = abilityName2; - want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); @@ -2000,9 +1996,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_3800, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); // Back Ability H1(singletop) - params["shouldReturn"] = abilityName2; - want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); - STAbilityUtil::StartAbility(want, abilityMs_); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); @@ -2080,11 +2075,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4000, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName1, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); // Terminate Ability G1(SI) - params["shouldReturn"] = abilityName1; - want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); - EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnNewWant, abilityStateCountOne), 0); - EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); @@ -2127,9 +2119,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4100, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName2, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); // terminate Ability G2(singletop) - params["shouldReturn"] = abilityName2; - want = STAbilityUtil::MakeWant("device", abilityName2, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); @@ -2176,11 +2167,9 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4200, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); // terminate Ability H1(singletop) - params["shouldReturn"] = abilityName2; - want = STAbilityUtil::MakeWant("device", abilityName2, bundleName2, params); - STAbilityUtil::StartAbility(want, abilityMs_); - EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); - EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnNewWant, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); + EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); @@ -2236,15 +2225,11 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_4300, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName1, AbilityState_Test::BACKGROUND, AbilityState_Test::MOVING_BACKGROUND); // terminate Ability G1(SI) - params["shouldReturn"] = abilityName1; - want = STAbilityUtil::MakeWant("device", abilityName1, bundleName1, params); - STAbilityUtil::StartAbility(want, abilityMs_); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); - // terminate Ability G1(SI), Launcher Ability State Is ACTIVE - ExpectAbilityCurrentState(launcherAbilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING, DUMP_ALL); - GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_4300 end"; } @@ -2768,7 +2753,6 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5500, Function | MediumTest | Leve STAbilityUtil::StopAbility(terminatePageAbility, 0, abilityName2); - EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnForeground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); @@ -2777,6 +2761,7 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5500, Function | MediumTest | Leve ExpectAbilityCurrentState(abilityName, AbilityState_Test::ACTIVE, AbilityState_Test::ACTIVATING); // ability "N2" not in stack ExpectAbilityNumInStack(abilityName2, 0); + ShowDump(); GTEST_LOG_(INFO) << "AmsPageAbilityTest AMS_Page_Ability_5500 end"; } @@ -2884,11 +2869,12 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5800, Function | MediumTest | Leve std::string bundleName = bundleNameBase + "N"; std::string abilityName = abilityNameBase + "N1"; MAP_STR_STR params; - params["shouldReturn"] = abilityName; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); @@ -2918,7 +2904,6 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5900, Function | MediumTest | Leve MAP_STR_STR params; params["targetBundle"] = bundleName; params["targetAbility"] = abilityName2; - params["shouldReturn"] = abilityName2; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); @@ -2926,6 +2911,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_5900, Function | MediumTest | Leve EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); @@ -2958,7 +2945,6 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6000, Function | MediumTest | Leve MAP_STR_STR params; params["targetBundle"] = bundleName2; params["targetAbility"] = abilityName2; - params["shouldReturn"] = abilityName2; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); @@ -2966,6 +2952,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6000, Function | MediumTest | Leve EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnInactive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnBackground, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnActive, abilityStateCountTwo), 0); @@ -2997,7 +2985,6 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6100, Function | MediumTest | Leve MAP_STR_STR params; params["targetBundle"] = bundleName; params["targetAbility"] = abilityName2; - params["shouldReturn"] = abilityName; Want want = STAbilityUtil::MakeWant("device", abilityName, bundleName, params); STAbilityUtil::StartAbility(want, abilityMs_); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStart, abilityStateCountOne), 0); @@ -3006,6 +2993,8 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6100, Function | MediumTest | Leve EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStart, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountOne), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnBackground, abilityStateCountOne), 0); + int eventCode = 0; + STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName + abilityStateOnStop, abilityStateCountOne), 0); // ability "N1" not in stack(terminated) @@ -3393,14 +3382,18 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6700, Function | MediumTest | Leve STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName5); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); MissionStackInfo missionStackInfo; GetAllStackInfo(missionStackInfo); EXPECT_TRUE(missionStackInfo.missionRecords.size() == 0); @@ -3450,14 +3443,18 @@ HWTEST_F(AmsPageAbilityTest, AMS_Page_Ability_6800, Function | MediumTest | Leve STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName5); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName5 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName3); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName3 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName2); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnActive, abilityStateCountTwo), 0); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName2 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); STAbilityUtil::PublishEvent(terminatePageAbility, eventCode, abilityName1); EXPECT_EQ(STAbilityUtil::WaitCompleted(event_, abilityName1 + abilityStateOnStop, abilityStateCountOne), 0); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); MissionStackInfo missionStackInfo; GetAllStackInfo(missionStackInfo); EXPECT_TRUE(missionStackInfo.missionRecords.size() == 0); diff --git a/test/systemtest/common/ams/ams_power_test/BUILD.gn b/test/systemtest/common/ams/ams_power_test/BUILD.gn old mode 100644 new mode 100755 index a8f782b54c1757ff8c7e06b8f8b3dc4aefeed597..b7e7aa63e1f7f5629463b011cb82ccc1a3f3bfb2 --- a/test/systemtest/common/ams/ams_power_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_power_test/BUILD.gn @@ -21,6 +21,7 @@ ohos_systemtest("ams_power_test") { "//foundation/distributedschedule/safwk/services/safwk/include", "${appexecfwk_path}/test/resource/amssystemtestability/abilitySrc/common", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -47,6 +48,7 @@ ohos_systemtest("ams_power_test") { "${appexecfwk_path}/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_power_test/ams_power_test.cpp b/test/systemtest/common/ams/ams_power_test/ams_power_test.cpp index 97a34cd8afeab977ae2323290a5178df77843ef5..3bb00b27a4e2b0923b9f731f209e1933e2171f7b 100644 --- a/test/systemtest/common/ams/ams_power_test/ams_power_test.cpp +++ b/test/systemtest/common/ams/ams_power_test/ams_power_test.cpp @@ -119,13 +119,11 @@ public: static sptr abilityMs_; static STtools::Event event_; static std::shared_ptr subscriber_; - static int *memTestValue_; }; sptr AmsPowerTest::appMs_ = nullptr; sptr AmsPowerTest::abilityMs_ = nullptr; STtools::Event AmsPowerTest::event_ = STtools::Event(); -int *AmsPowerTest::memTestValue_ = nullptr; std::shared_ptr AmsPowerTest::subscriber_ = nullptr; void AmsPowerTest::SetUpTestCase(void) @@ -160,9 +158,6 @@ void AmsPowerTest::SetUp(void) void AmsPowerTest::TearDown(void) { GTEST_LOG_(INFO) << "void AmsPowerTest::TearDown(void)"; - if (memTestValue_) { - delete[] memTestValue_; - } STAbilityUtil::RemoveStack(1, abilityMs_, WAIT_TIME, WAIT_LAUNCHER_OK); std::vector vecBundleName; for (const auto &suffix : bundleNameSuffix) { @@ -217,6 +212,10 @@ void AmsPowerTest::CheckAbilityStateByName(const std::string &abilityName, const EXPECT_NE(pos, result.end()); MTDumpUtil::GetInstance()->GetAll("State", info, result); EXPECT_TRUE(pos < result.end()); + if (pos == result.end()) { + HILOG_ERROR("pos == result.end()"); + return; + } // ability state if (midState != "") { bool compareResult = ((*pos == state) || (*pos == midState)); diff --git a/test/systemtest/common/ams/ams_service_ability_test/BUILD.gn b/test/systemtest/common/ams/ams_service_ability_test/BUILD.gn index 082648f0e9f5a7dc9c72d8aea3d146ff0cdb63a3..e293251fc1af36a4391d50308f79e460ea7080e6 100755 --- a/test/systemtest/common/ams/ams_service_ability_test/BUILD.gn +++ b/test/systemtest/common/ams/ams_service_ability_test/BUILD.gn @@ -22,6 +22,7 @@ ohos_systemtest("ams_service_ability_test") { include_dirs = [ "//foundation/distributedschedule/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", + "//third_party/jsoncpp/include", ] sources = [ @@ -49,6 +50,7 @@ ohos_systemtest("ams_service_ability_test") { "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp index 07e31570359dceb49dbc3df00728dc3c71c23379..2562f1e8637d7ae029041ea399f0bf11d8b366be 100644 --- a/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp +++ b/test/systemtest/common/ams/ams_service_ability_test/ams_service_ability_test.cpp @@ -331,7 +331,7 @@ void AmsServiceAbilityTest::CheckAbilityStateByName( // ability exist EXPECT_NE(pos, result.end()); MTDumpUtil::GetInstance()->GetAll("State", info, result); - ASSERT_TRUE(pos < result.end()); + EXPECT_TRUE(pos < result.end()); // ability state EXPECT_EQ(Trim(*pos), state); } diff --git a/test/systemtest/common/ams/tool/BUILD.gn b/test/systemtest/common/ams/tool/BUILD.gn old mode 100644 new mode 100755 index b92bc15c53b91fa13608909aae4557d774fda899..f63448383715c80efc0b4817af64bd66daa482db --- a/test/systemtest/common/ams/tool/BUILD.gn +++ b/test/systemtest/common/ams/tool/BUILD.gn @@ -16,6 +16,7 @@ import("//foundation/appexecfwk/standard/appexecfwk.gni") config("system_test_ability_util_config") { include_dirs = [ + "//third_party/jsoncpp/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//foundation/distributedschedule/safwk/services/safwk/include", ] @@ -48,6 +49,7 @@ ohos_shared_library("system_test_ability_util_lib") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/test/systemtest/common/bms/BUILD.gn b/test/systemtest/common/bms/BUILD.gn index ebf10ab58e005ce961bd6bf48c8aaf92d11b0e78..cc0943c8516a34362081e78151e7b478787c6cf7 100755 --- a/test/systemtest/common/bms/BUILD.gn +++ b/test/systemtest/common/bms/BUILD.gn @@ -9,7 +9,7 @@ # 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. +# limitations under the License. import("//build/ohos.gni") import("//foundation/appexecfwk/standard/appexecfwk.gni") @@ -72,6 +72,7 @@ group("systemtest_bms") { deps = [ "acts_bms_kit_system_test:systemtest", "bms_install_system_test:systemtest", + "bms_launcher_service_system_test:systemtest", "bms_search_system_test:systemtest", "bms_uninstall_system_test:systemtest", ] diff --git a/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp b/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp old mode 100755 new mode 100644 index f43c80c6324c4c79923174b4731a3a0f35b454e2..a7561ee6b6bc0c186ad33d508896e3ecd3c39f80 --- a/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp +++ b/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp @@ -14,6 +14,7 @@ */ #include +#include #include #include @@ -31,6 +32,7 @@ using OHOS::AAFwk::Want; using namespace testing::ext; +using namespace std::chrono_literals; namespace { const std::string THIRD_BUNDLE_PATH = "/data/test/bms_bundle/"; @@ -58,6 +60,9 @@ public: virtual ~BundleStatusCallbackImpl() override; virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) override; + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override{}; + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override{}; + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override{}; private: DISALLOW_COPY_AND_MOVE(BundleStatusCallbackImpl); @@ -181,7 +186,6 @@ public: const std::string &bundleName, const std::string &modulePackage, std::vector &resvec); static sptr GetBundleMgrProxy(); static sptr GetInstallerProxy(); - bool CreateFile(const std::string &path) const; void CheckBundleInfo(const uint32_t index, BundleInfo &bundleInfo) const; void CreateDir(const std::string &path) const; void CheckFileExist(const std::string &bundleName) const; @@ -225,7 +229,7 @@ void ActsBmsKitSystemTest::Install( installParam.installFlag = installFlag; installParam.userId = Constants::DEFAULT_USERID; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -246,7 +250,7 @@ void ActsBmsKitSystemTest::Uninstall(const std::string &bundleName, std::vector< InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -269,7 +273,7 @@ void ActsBmsKitSystemTest::HapUninstall( InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, modulePackage, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -312,62 +316,28 @@ sptr ActsBmsKitSystemTest::GetInstallerProxy() return installerProxy; } -bool ActsBmsKitSystemTest::CreateFile(const std::string &path) const -{ - if (path.size() > PATH_MAX) { - APP_LOGE("CreateFile the length of path is too long"); - return false; - } - - std::string realPath; - realPath.reserve(PATH_MAX); - realPath.resize(PATH_MAX - 1); - - if (realpath(path.c_str(), &(realPath[0])) != nullptr) { - APP_LOGW("CreateFile-translate:%{public}s already exist path", realPath.c_str()); - return true; - } - - mode_t mode = 0666; - int fd = open(realPath.c_str(), O_RDWR | O_CREAT, mode); - if (fd == -1) { - APP_LOGE("CreateFile-open:%{public}s error", realPath.c_str()); - return false; - } - if (close(fd) != 0) { - APP_LOGW("CreateFile-close:%{public}s error", realPath.c_str()); - return false; - } - - if (access(realPath.c_str(), F_OK) != 0) { - APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); - return false; - } - return true; -} - void ActsBmsKitSystemTest::CheckFileExist(const std::string &bundleName) const { int bundleDataExist = access((BUNDLE_DATA_ROOT_PATH + bundleName).c_str(), F_OK); - ASSERT_EQ(bundleDataExist, 0) << "the bundle data dir doesn't exist: " << bundleName; + EXPECT_EQ(bundleDataExist, 0) << "the bundle data dir doesn't exist: " << bundleName; } void ActsBmsKitSystemTest::CheckFileExist(const std::string &bundleName, const std::string &modulePackage) const { int bundleDataExist = access((BUNDLE_DATA_ROOT_PATH + bundleName + "/" + modulePackage).c_str(), F_OK); - ASSERT_EQ(bundleDataExist, 0) << "the bundle data dir doesn't exist: " << bundleName; + EXPECT_EQ(bundleDataExist, 0) << "the bundle data dir doesn't exist: " << bundleName; } void ActsBmsKitSystemTest::CheckFileNonExist(const std::string &bundleName) const { int bundleDataExist = access((BUNDLE_DATA_ROOT_PATH + bundleName).c_str(), F_OK); - ASSERT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << bundleName; + EXPECT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << bundleName; } void ActsBmsKitSystemTest::CheckFileNonExist(const std::string &bundleName, const std::string &modulePackage) const { int bundleDataExist = access((BUNDLE_DATA_ROOT_PATH + bundleName + "/" + modulePackage).c_str(), F_OK); - ASSERT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << bundleName; + EXPECT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << bundleName; } void ActsBmsKitSystemTest::CheckBundleInfo(const uint32_t index, BundleInfo &bundleInfo) const @@ -404,7 +374,7 @@ void ActsBmsKitSystemTest::CheckBundleInfo(const uint32_t index, BundleInfo &bun EXPECT_EQ(iter->bundleName, BASE_BUNDLE_NAME + std::to_string(index)); EXPECT_EQ(iter->description, ""); EXPECT_EQ(iter->label, "bmsThirdBundle_A2 Ability"); - EXPECT_EQ(iter->moduleName, "bmsThirdBundle1"); + EXPECT_EQ(iter->moduleName, "testability"); std::cout << "abilityInfo-moduleName:" << iter->moduleName << std::endl; EXPECT_EQ(iter->uri, ""); EXPECT_EQ(iter->visible, true); @@ -467,11 +437,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0100, Function | MediumTest | Level Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bool getInfoResult = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -480,7 +450,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0100, Function | MediumTest | Level resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetBundleInfo_0100 failed - cycle count: %{public}d", i); break; @@ -513,11 +483,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0200, Function | MediumTest | Level Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bool getInfoResult = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); @@ -526,7 +496,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0200, Function | MediumTest | Level resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetBundleInfo_0200 failed - cycle count: %{public}d", i); @@ -561,11 +531,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0300, Function | MediumTest | Level CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bool getInfoResult = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); @@ -574,7 +544,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0300, Function | MediumTest | Level resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetBundleInfo_0300 failed - cycle count: %{public}d", i); @@ -609,11 +579,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0400, Function | MediumTest | Level CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_NO_PROFILE]") << "Success!"; + EXPECT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_NO_PROFILE]") << "Success!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bool getInfoResult = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); @@ -652,11 +622,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0500, Function | MediumTest | Level CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Failure[ERR_INSTALL_INVALID_HAP_NAME]"); + EXPECT_EQ(installResult, "Failure[ERR_INSTALL_INVALID_HAP_NAME]"); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bool getInfoResult = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); @@ -694,11 +664,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0600, Function | MediumTest | Level CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } appName = BASE_BUNDLE_NAME + "e"; BundleInfo bundleInfo; @@ -708,7 +678,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0600, Function | MediumTest | Level appName = BASE_BUNDLE_NAME + "1"; Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (getInfoResult) { APP_LOGI("GetBundleInfo_0600 failed - cycle count: %{public}d", i); @@ -742,7 +712,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0700, Function | MediumTest | Level sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; @@ -787,13 +757,13 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0800, Function | MediumTest | Level Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_TRUE(getInfoResult); @@ -802,7 +772,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0800, Function | MediumTest | Level resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetBundleInfo_0800 failed - cycle count: %{public}d", i); break; @@ -834,13 +804,13 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0900, Function | MediumTest | Level Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_TRUE(getInfoResult); @@ -849,7 +819,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfo_0900, Function | MediumTest | Level resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetBundleInfo_0900 failed - cycle count: %{public}d", i); break; @@ -882,12 +852,12 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfos_0100, Function | MediumTest | Leve std::string hapFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle" + std::to_string(i) + ".hap"; Install(hapFilePath, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; } sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector bundleInfos; bool getInfoResult = bundleMgrProxy->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos); @@ -906,7 +876,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfos_0100, Function | MediumTest | Leve std::vector resvec2; Uninstall(appName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; } if (!getInfoResult) { APP_LOGI("GetBundleInfos_0100 failed - cycle count: %{public}d", i); @@ -936,7 +906,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfos_0200, Function | MediumTest | Leve sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector bundleInfos; @@ -955,7 +925,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfos_0200, Function | MediumTest | Leve break; } } - EXPECT_EQ(count, 3); + EXPECT_GE(count, 2); if (!getInfoResult) { APP_LOGI("GetBundleInfos_0200 failed - cycle count: %{public}d", i); @@ -991,12 +961,12 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0100, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; @@ -1007,7 +977,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0100, Function | MediumTest | resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetApplicationInfo_0100 failed - cycle count: %{public}d", i); @@ -1042,12 +1012,12 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0200, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; @@ -1055,11 +1025,10 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0200, Function | MediumTest | appName, ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, userId, appInfo); std::string permission = commonTool.VectorToStr(appInfo.permissions); EXPECT_TRUE(getInfoResult); - std::cout << permission << std::endl; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetApplicationInfo_0200 failed - cycle count: %{public}d", i); @@ -1094,12 +1063,12 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0300, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; @@ -1111,7 +1080,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0300, Function | MediumTest | appName = BASE_BUNDLE_NAME + "1"; Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (getInfoResult) { APP_LOGI("GetApplicationInfo_0300 failed - cycle count: %{public}d", i); @@ -1146,12 +1115,12 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0400, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; @@ -1159,13 +1128,10 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0400, Function | MediumTest | bundleMgrProxy->GetApplicationInfo(appName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); EXPECT_TRUE(getInfoResult); EXPECT_EQ(appInfo.name, appName); - std::cout << appInfo.description << std::endl; - std::cout << appInfo.iconPath << std::endl; - std::cout << appInfo.supportedModes << std::endl; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetApplicationInfo_0400 failed - cycle count: %{public}d", i); @@ -1196,7 +1162,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0500, Function | MediumTest | sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; @@ -1239,17 +1205,17 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0600, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success"); + EXPECT_EQ(uninstallResult, "Success"); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; int userId = -1; @@ -1289,14 +1255,14 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0700, Function | MediumTest | Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetApplicationInfo(appName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); @@ -1306,7 +1272,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfo_0700, Function | MediumTest | resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetApplicationInfo_0700 failed - cycle count: %{public}d", i); break; @@ -1337,7 +1303,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfos_0100, Function | MediumTest | sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string installResult; int userId = Constants::DEFAULT_USERID; @@ -1347,7 +1313,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfos_0100, Function | MediumTest | std::string appName = BASE_BUNDLE_NAME + std::to_string(i - 5); Install(hapFilePath, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::vector appInfos; bool getInfoResult = @@ -1356,7 +1322,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfos_0100, Function | MediumTest | resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isSubStrExist = false; for (auto iter = appInfos.begin(); iter != appInfos.end(); iter++) { @@ -1396,7 +1362,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfos_0200, Function | MediumTest | sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector appInfos; bool getInfoResult = @@ -1415,7 +1381,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetApplicationInfos_0200, Function | MediumTest | break; } } - EXPECT_EQ(count, 3); + EXPECT_GE(count, 2); if (!getInfoResult) { APP_LOGI("GetApplicationInfos_0200 failed - cycle count: %{public}d", i); @@ -1449,7 +1415,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleArchiveInfo_0100, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleArchiveInfo(hapFilePath, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -1491,7 +1457,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleArchiveInfo_0200, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleArchiveInfo(hapFilePath, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); @@ -1538,7 +1504,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleArchiveInfo_0300, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string hapFilePath = THIRD_BUNDLE_PATH + "tt.hap"; bool getInfoResult = @@ -1576,7 +1542,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleArchiveInfo_0400, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleArchiveInfo(hapFilePath, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -1614,7 +1580,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleArchiveInfo_0500, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleArchiveInfo(hapFilePath, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -1653,11 +1619,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetUidByBundleName_0100, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int userId = Constants::DEFAULT_USERID; int uid = bundleMgrProxy->GetUidByBundleName(bundleName, userId); @@ -1666,7 +1632,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetUidByBundleName_0100, Function | MediumTest | resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (uid == Constants::INVALID_UID) { APP_LOGI("GetUidByBundleName_0100 failed - cycle count: %{public}d", i); @@ -1701,11 +1667,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetUidByBundleName_0200, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int userId = Constants::INVALID_USERID; int uid = bundleMgrProxy->GetUidByBundleName(bundleName, userId); @@ -1713,7 +1679,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetUidByBundleName_0200, Function | MediumTest | resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (uid == Constants::INVALID_UID) { APP_LOGI("GetUidByBundleName_0200 failed - cycle count: %{public}d", i); @@ -1749,11 +1715,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetUidByBundleName_0300, Function | MediumTest | CommonTool commonTool; int userId = Constants::DEFAULT_USERID; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleName = BASE_BUNDLE_NAME + "e"; int uid = bundleMgrProxy->GetUidByBundleName(bundleName, userId); @@ -1763,7 +1729,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetUidByBundleName_0300, Function | MediumTest | bundleName = BASE_BUNDLE_NAME + "1"; Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (uid != Constants::INVALID_UID) { APP_LOGI("GetUidByBundleName_0300 failed - cycle count: %{public}d", i); @@ -1793,7 +1759,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetUidByBundleName_0400, Function | MediumTest | sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int userId = Constants::DEFAULT_USERID; @@ -1833,11 +1799,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleNameForUid_0100, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -1850,7 +1816,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleNameForUid_0100, Function | MediumTest | resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("GetBundleNameForUid_0100 failed - cycle count: %{public}d", i); @@ -1879,7 +1845,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleNameForUid_0200, Function | MediumTest | sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; @@ -1920,7 +1886,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleNameForUid_0300, Function | MediumTest | sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int uid = Constants::INVALID_UID; std::string bundleName; @@ -1960,18 +1926,18 @@ HWTEST_F(ActsBmsKitSystemTest, GetAppType_0100, Function | MediumTest | Level1) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appType = bundleMgrProxy->GetAppType(appName); EXPECT_EQ(appType, "third-party"); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (std::strcmp(appType.c_str(), "third-party") != 0) { APP_LOGI("GetAppType_0100 failed - cycle count: %{public}d", i); @@ -2003,7 +1969,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetAppType_0200, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appType = bundleMgrProxy->GetAppType(SYSTEM_SETTINGS_BUNDLE_NAME); EXPECT_EQ(appType, "system"); @@ -2042,18 +2008,18 @@ HWTEST_F(ActsBmsKitSystemTest, GetAppType_0300, Function | MediumTest | Level2) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appType = bundleMgrProxy->GetAppType(errName); EXPECT_EQ(appType, Constants::EMPTY_STRING); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (std::strcmp(appType.c_str(), (Constants::EMPTY_STRING).c_str()) != 0) { APP_LOGI("GetAppType_0300 failed - cycle count: %{public}d", i); @@ -2088,11 +2054,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetAppType_0400, Function | MediumTest | Level2) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success"); + EXPECT_NE(installResult, "Success"); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appType = bundleMgrProxy->GetAppType(appName); EXPECT_EQ(appType, Constants::EMPTY_STRING); @@ -2130,11 +2096,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetAppType_0500, Function | MediumTest | Level2) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success"); + EXPECT_NE(installResult, "Success"); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appType = bundleMgrProxy->GetAppType(appName); EXPECT_EQ(appType, Constants::EMPTY_STRING); @@ -2173,18 +2139,18 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityLabel_0100, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string abilityLabel = bundleMgrProxy->GetAbilityLabel(appName, abilityName); EXPECT_NE(abilityLabel, "EMPTY_STRING"); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (std::strcmp(abilityLabel.c_str(), "EMPTY_STRING") == 0) { APP_LOGI("GetAbilityLabel_0100 failed - cycle count: %{public}d", i); @@ -2218,7 +2184,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityLabel_0200, Function | MediumTest | Lev sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string abilityLabel = bundleMgrProxy->GetAbilityLabel(appName, abilityName); EXPECT_NE(abilityLabel, "EMPTY_STRING"); @@ -2257,11 +2223,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityLabel_0300, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string errAppName = BASE_BUNDLE_NAME + "e"; std::string abilityLabel = bundleMgrProxy->GetAbilityLabel(errAppName, abilityName); @@ -2269,7 +2235,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityLabel_0300, Function | MediumTest | Lev resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (std::strcmp(abilityLabel.c_str(), (Constants::EMPTY_STRING).c_str()) != 0) { APP_LOGI("GetAbilityLabel_0300 failed - cycle count: %{public}d", i); @@ -2305,18 +2271,18 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityLabel_0400, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string abilityLabel = bundleMgrProxy->GetAbilityLabel(appName, errAbilityName); EXPECT_EQ(abilityLabel, Constants::EMPTY_STRING); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (std::strcmp(abilityLabel.c_str(), (Constants::EMPTY_STRING).c_str()) != 0) { APP_LOGI("GetAbilityLabel_0400 failed - cycle count: %{public}d", i); @@ -2352,11 +2318,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityLabel_0500, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success"); + EXPECT_NE(installResult, "Success"); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string abilityLabel = bundleMgrProxy->GetAbilityLabel(appName, abilityName); EXPECT_EQ(abilityLabel, Constants::EMPTY_STRING); @@ -2395,11 +2361,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityLabel_0600, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success"); + EXPECT_NE(installResult, "Success"); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string abilityLabel = bundleMgrProxy->GetAbilityLabel(appName, abilityName); EXPECT_EQ(abilityLabel, Constants::EMPTY_STRING); @@ -2437,7 +2403,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0100, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = appName; @@ -2446,21 +2412,21 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0100, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_TRUE(queryResult); EXPECT_EQ(hapModuleInfo.name, "com.third.hiworld.example.h1"); - EXPECT_EQ(hapModuleInfo.moduleName, "bmsThirdBundle1"); + EXPECT_EQ(hapModuleInfo.moduleName, "testability"); EXPECT_EQ(hapModuleInfo.description, ""); EXPECT_EQ(hapModuleInfo.label, "bmsThirdBundle_A1 Ability"); - std::cout << commonTool.VectorToStr(hapModuleInfo.deviceTypes) << std::endl; + EXPECT_EQ(commonTool.VectorToStr(hapModuleInfo.deviceTypes), "tvcar"); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("GetHapModuleInfo_0100 failed - cycle count: %{public}d", i); @@ -2495,7 +2461,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = appName; @@ -2504,14 +2470,14 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_TRUE(queryResult); EXPECT_EQ(hapModuleInfo.name, "com.third.hiworld.example.h1"); - EXPECT_EQ(hapModuleInfo.moduleName, "bmsThirdBundle2"); + EXPECT_EQ(hapModuleInfo.moduleName, "testability"); EXPECT_EQ(hapModuleInfo.label, "bmsThirdBundle_A1 Ability"); - std::cout << commonTool.VectorToStr(hapModuleInfo.deviceTypes) << std::endl; + EXPECT_EQ(commonTool.VectorToStr(hapModuleInfo.deviceTypes), "tvcar"); bool isSubStrExist = false; for (int i = 1; i <= 2; i++) { std::string abilityName = "" + std::to_string(i); @@ -2526,7 +2492,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("GetHapModuleInfo_0200 failed - cycle count: %{public}d", i); @@ -2561,7 +2527,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0300, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = appName; @@ -2570,18 +2536,17 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0300, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_TRUE(queryResult); EXPECT_EQ(hapModuleInfo.name, "com.third.hiworld.example.h1"); - EXPECT_EQ(hapModuleInfo.moduleName, "bmsThirdBundle3"); - std::cout << commonTool.VectorToStr(hapModuleInfo.deviceTypes) << std::endl; + EXPECT_EQ(hapModuleInfo.moduleName, "testability"); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("GetHapModuleInfo_0300 failed - cycle count: %{public}d", i); @@ -2616,7 +2581,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0400, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = "error_bundleName"; @@ -2626,14 +2591,14 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0400, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_FALSE(queryResult); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (queryResult) { APP_LOGI("GetHapModuleInfo_0400 failed - cycle count: %{public}d", i); @@ -2669,15 +2634,15 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0500, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_TRUE(queryResult); EXPECT_EQ(hapModuleInfo.name, "com.ohos.settings"); - EXPECT_EQ(hapModuleInfo.moduleName, ".MyApplication"); + EXPECT_EQ(hapModuleInfo.moduleName, "entry"); EXPECT_EQ(hapModuleInfo.label, "$string:app_name"); CommonTool commonTool; - std::cout << commonTool.VectorToStr(hapModuleInfo.deviceTypes) << std::endl; + EXPECT_EQ(commonTool.VectorToStr(hapModuleInfo.deviceTypes), "phone"); if (!queryResult) { APP_LOGI("GetHapModuleInfo_0500 failed - cycle count: %{public}d", i); @@ -2712,7 +2677,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0600, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success"); + EXPECT_NE(installResult, "Success"); AbilityInfo abilityInfo; abilityInfo.bundleName = appName; @@ -2721,7 +2686,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0600, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_FALSE(queryResult); @@ -2759,7 +2724,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0700, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success") << "install fail!"; + EXPECT_NE(installResult, "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = appName; @@ -2768,7 +2733,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0700, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_FALSE(queryResult); @@ -2807,17 +2772,17 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0100, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(bundleStatusCallback, nullptr); + EXPECT_NE(bundleStatusCallback, nullptr); bundleStatusCallback->SetBundleName(appName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(bundleStatusCallback); Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; bool unRegResult = bundleMgrProxy->UnregisterBundleStatusCallback(); EXPECT_TRUE(unRegResult); @@ -2825,7 +2790,7 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0100, Function | MediumTest | Level1) resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!unRegResult) { APP_LOGI("Callback_0100 failed - cycle count: %{public}d", i); @@ -2861,17 +2826,17 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0200, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(bundleStatusCallback, nullptr); + EXPECT_NE(bundleStatusCallback, nullptr); bundleStatusCallback->SetBundleName(appName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(bundleStatusCallback); Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success"); + EXPECT_NE(installResult, "Success"); bool unRegResult = bundleMgrProxy->UnregisterBundleStatusCallback(); EXPECT_TRUE(unRegResult); @@ -2912,29 +2877,29 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0300, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(bundleStatusCallback, nullptr); + EXPECT_NE(bundleStatusCallback, nullptr); bundleStatusCallback->SetBundleName(appName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(bundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); Install(secondFilePath, InstallFlag::REPLACE_EXISTING, resvec); std::string upgradeResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(upgradeResult, "Success") << "upgrade fail!"; + EXPECT_EQ(upgradeResult, "Success") << "upgrade fail!"; bool unRegResult = bundleMgrProxy->UnregisterBundleStatusCallback(); EXPECT_TRUE(unRegResult); std::vector resvec2; Uninstall(appName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!unRegResult) { APP_LOGI("Callback_0300 failed - cycle count: %{public}d", i); @@ -2973,29 +2938,29 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0400, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(bundleStatusCallback, nullptr); + EXPECT_NE(bundleStatusCallback, nullptr); bundleStatusCallback->SetBundleName(appName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(bundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); Install(secondFilePath, InstallFlag::REPLACE_EXISTING, resvec); std::string upgradeResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(upgradeResult, "Success") << "upgrade fail!"; + EXPECT_EQ(upgradeResult, "Success") << "upgrade fail!"; bool unRegResult = bundleMgrProxy->UnregisterBundleStatusCallback(); EXPECT_TRUE(unRegResult); std::vector resvec2; Uninstall(appName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!unRegResult) { APP_LOGI("Callback_0400 failed - cycle count: %{public}d", i); @@ -3034,29 +2999,29 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0500, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(bundleStatusCallback, nullptr); + EXPECT_NE(bundleStatusCallback, nullptr); bundleStatusCallback->SetBundleName(appName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(bundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); Install(secondFilePath, InstallFlag::REPLACE_EXISTING, resvec); std::string upgradeResult = commonTool.VectorToStr(resvec); - ASSERT_NE(upgradeResult, "Success") << "upgrade success!"; + EXPECT_NE(upgradeResult, "Success") << "upgrade success!"; bool unRegResult = bundleMgrProxy->UnregisterBundleStatusCallback(); EXPECT_TRUE(unRegResult); std::vector resvec2; Uninstall(appName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!unRegResult) { APP_LOGI("Callback_0500 failed - cycle count: %{public}d", i); @@ -3092,23 +3057,23 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0600, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(bundleStatusCallback, nullptr); + EXPECT_NE(bundleStatusCallback, nullptr); bundleStatusCallback->SetBundleName(appName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(bundleStatusCallback); Install(filePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; bool clearResult = bundleMgrProxy->ClearBundleStatusCallback(bundleStatusCallback); EXPECT_TRUE(clearResult); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!clearResult) { APP_LOGI("Callback_0600 failed - cycle count: %{public}d", i); @@ -3148,26 +3113,26 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0700, Function | MediumTest | Level1) CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(firstBundleStatusCallback, nullptr); + EXPECT_NE(firstBundleStatusCallback, nullptr); firstBundleStatusCallback->SetBundleName(firstAppName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string firstinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(firstinstallResult, "Success") << "install fail!"; + EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(secondBundleStatusCallback, nullptr); + EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); std::string secondinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(secondinstallResult, "Success") << "install fail!"; + EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; bool clearResult = bundleMgrProxy->ClearBundleStatusCallback(firstBundleStatusCallback); EXPECT_TRUE(clearResult); @@ -3175,11 +3140,11 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0700, Function | MediumTest | Level1) std::vector resvec2; Uninstall(firstAppName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!clearResult) { APP_LOGI("Callback_0700 failed - cycle count: %{public}d", i); @@ -3219,26 +3184,26 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(firstBundleStatusCallback, nullptr); + EXPECT_NE(firstBundleStatusCallback, nullptr); firstBundleStatusCallback->SetBundleName(firstAppName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string firstinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(firstinstallResult, "Success") << "install fail!"; + EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(secondBundleStatusCallback, nullptr); + EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); std::string secondinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(secondinstallResult, "Success") << "install fail!"; + EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; bool clearResult = bundleMgrProxy->ClearBundleStatusCallback(secondBundleStatusCallback); EXPECT_TRUE(clearResult); @@ -3246,11 +3211,11 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) std::vector resvec2; Uninstall(firstAppName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!clearResult) { APP_LOGI("Callback_0800 failed - cycle count: %{public}d", i); @@ -3291,26 +3256,26 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0900, Function | MediumTest | Level1) CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(firstBundleStatusCallback, nullptr); + EXPECT_NE(firstBundleStatusCallback, nullptr); firstBundleStatusCallback->SetBundleName(firstAppName); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string firstinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(firstinstallResult, "Success") << "install fail!"; + EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(secondBundleStatusCallback, nullptr); + EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); std::string secondinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(secondinstallResult, "Success") << "install fail!"; + EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; bool clearResult1 = bundleMgrProxy->ClearBundleStatusCallback(firstBundleStatusCallback); EXPECT_TRUE(clearResult1); @@ -3320,11 +3285,11 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0900, Function | MediumTest | Level1) std::vector resvec2; Uninstall(firstAppName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!clearResult1 && !clearResult2) { APP_LOGI("Callback_0900 failed - cycle count: %{public}d", i); @@ -3360,30 +3325,36 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0100, Function | MediumTest CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; - - const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/name1.txt"; - const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/name2.txt"; + EXPECT_EQ(installResult, "Success") << "install fail!"; + std::this_thread::sleep_for(5000ms); + system("aa start -a PageAbilityDemo -b com.third.hiworld.example1"); + std::this_thread::sleep_for(1000ms); + const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/name1.txt"; + const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/name2.txt"; + int name1Exist = access(testCacheFileNamE1.c_str(), F_OK); + EXPECT_EQ(name1Exist, 0); + int name2Exist = access(testCacheFileNamE2.c_str(), F_OK); + EXPECT_EQ(name2Exist, 0); sptr bundleCleanCacheCallback = (new (std::nothrow) CleanCacheCallBackImpl()); - ASSERT_NE(bundleCleanCacheCallback, nullptr); + EXPECT_NE(bundleCleanCacheCallback, nullptr); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->CleanBundleCacheFiles(appName, bundleCleanCacheCallback); bool cleanCacheResult = bundleCleanCacheCallback->GetSucceededResult(); EXPECT_TRUE(cleanCacheResult); - int name1Exist = access(testCacheFileNamE1.c_str(), F_OK); + name1Exist = access(testCacheFileNamE1.c_str(), F_OK); EXPECT_NE(name1Exist, 0) << "the cache test file1 exists."; - int name2Exist = access(testCacheFileNamE2.c_str(), F_OK); + name2Exist = access(testCacheFileNamE2.c_str(), F_OK); EXPECT_NE(name2Exist, 0) << "the cache test file2 exists."; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!cleanCacheResult) { APP_LOGI("CleanBundleCacheFiles_0100 failed - cycle count: %{public}d", i); @@ -3419,30 +3390,35 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0200, Function | MediumTest CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; - - const std::string testCacheDiR1 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/testDir1"; - const std::string testCacheDiR2 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/testDir2"; - + EXPECT_EQ(installResult, "Success") << "install fail!"; + std::this_thread::sleep_for(5000ms); + system("aa start -a PageAbilityDemo -b com.third.hiworld.example2"); + std::this_thread::sleep_for(1000ms); + const std::string testCacheDiR1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir1"; + const std::string testCacheDiR2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir2"; + int name1Exist = access(testCacheDiR1.c_str(), F_OK); + EXPECT_EQ(name1Exist, 0); + int name2Exist = access(testCacheDiR2.c_str(), F_OK); + EXPECT_EQ(name2Exist, 0); sptr bundleCleanCacheCallback = (new (std::nothrow) CleanCacheCallBackImpl()); - ASSERT_NE(bundleCleanCacheCallback, nullptr); + EXPECT_NE(bundleCleanCacheCallback, nullptr); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->CleanBundleCacheFiles(appName, bundleCleanCacheCallback); bool cleanCacheResult = bundleCleanCacheCallback->GetSucceededResult(); EXPECT_TRUE(cleanCacheResult); - int name1Exist = access(testCacheDiR1.c_str(), F_OK); + name1Exist = access(testCacheDiR1.c_str(), F_OK); EXPECT_NE(name1Exist, 0) << "the cache test dir1 exists."; - int name2Exist = access(testCacheDiR2.c_str(), F_OK); + name2Exist = access(testCacheDiR2.c_str(), F_OK); EXPECT_NE(name2Exist, 0) << "the cache test dir2 exists."; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!cleanCacheResult) { APP_LOGI("CleanBundleCacheFiles_0200 failed - cycle count: %{public}d", i); @@ -3472,34 +3448,37 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0300, Function | MediumTest bool result = false; for (int i = 1; i <= stLevel_.BMSLevel; i++) { std::vector resvec; - std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle44.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; - - const std::string testCacheFileName = - BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/dir1/dir2/dir3/dir4/dir5/dir6/name.txt"; - const std::string testCacheDir = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/dir1"; + EXPECT_EQ(installResult, "Success") << "install fail!"; + std::this_thread::sleep_for(5000ms); + system("aa start -a PageAbilityDemo -b com.third.hiworld.example1"); + std::this_thread::sleep_for(1000ms); + const std::string testCacheFileName = BUNDLE_DATA_ROOT_PATH + appName + "/cache/dir1/dir2/dir3/dir4/dir5/dir6"; + const std::string testCacheDir = BUNDLE_DATA_ROOT_PATH + appName + "/cache/dir1"; + int isExist = access(testCacheDir.c_str(), F_OK); + EXPECT_EQ(isExist, 0); sptr bundleCleanCacheCallback = (new (std::nothrow) CleanCacheCallBackImpl()); - ASSERT_NE(bundleCleanCacheCallback, nullptr); + EXPECT_NE(bundleCleanCacheCallback, nullptr); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->CleanBundleCacheFiles(appName, bundleCleanCacheCallback); bool cleanCacheResult = bundleCleanCacheCallback->GetSucceededResult(); EXPECT_TRUE(cleanCacheResult); - int isExist = access(testCacheDir.c_str(), F_OK); + isExist = access(testCacheDir.c_str(), F_OK); EXPECT_NE(isExist, 0) << "the cache test dir exists."; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!cleanCacheResult) { APP_LOGI("CleanBundleCacheFiles_0300 failed - cycle count: %{public}d", i); @@ -3529,38 +3508,43 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0400, Function | MediumTest bool result = false; for (int i = 1; i <= stLevel_.BMSLevel; i++) { std::vector resvec; - std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle45.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; - - const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/testDir1/name1.txt"; - const std::string testCacheDir1 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/testDir1"; - const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/testDir2/name2.txt"; - const std::string testCacheDir2 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/testDir2"; - + EXPECT_EQ(installResult, "Success") << "install fail!"; + std::this_thread::sleep_for(5000ms); + system("aa start -a PageAbilityDemo -b com.third.hiworld.example1"); + std::this_thread::sleep_for(1000ms); + const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir1/name1.txt"; + const std::string testCacheDir1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir1"; + const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir2/name2.txt"; + const std::string testCacheDir2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/testDir2"; + int name1Exist = access(testCacheDir1.c_str(), F_OK); + EXPECT_EQ(name1Exist, 0); + int name2Exist = access(testCacheDir2.c_str(), F_OK); + EXPECT_EQ(name2Exist, 0); sptr bundleCleanCacheCallback = (new (std::nothrow) CleanCacheCallBackImpl()); - ASSERT_NE(bundleCleanCacheCallback, nullptr); + EXPECT_NE(bundleCleanCacheCallback, nullptr); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->CleanBundleCacheFiles(appName, bundleCleanCacheCallback); bool cleanCacheResult = bundleCleanCacheCallback->GetSucceededResult(); EXPECT_TRUE(cleanCacheResult); - int name1Exist = access(testCacheDir1.c_str(), F_OK); + name1Exist = access(testCacheDir1.c_str(), F_OK); EXPECT_NE(name1Exist, 0) << "the cache test dir1 exists."; - int name2Exist = access(testCacheDir2.c_str(), F_OK); + name2Exist = access(testCacheDir2.c_str(), F_OK); EXPECT_NE(name2Exist, 0) << "the cache test dir2 exists."; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!cleanCacheResult) { APP_LOGI("CleanBundleCacheFiles_0400 failed - cycle count: %{public}d", i); @@ -3593,13 +3577,13 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0500, Function | MediumTest CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_NO_PROFILE]"); + EXPECT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_NO_PROFILE]"); sptr bundleCleanCacheCallback = (new (std::nothrow) CleanCacheCallBackImpl()); - ASSERT_NE(bundleCleanCacheCallback, nullptr); + EXPECT_NE(bundleCleanCacheCallback, nullptr); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool cleanCacheResult = bundleMgrProxy->CleanBundleCacheFiles(appName, bundleCleanCacheCallback); EXPECT_FALSE(cleanCacheResult); @@ -3636,14 +3620,14 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0600, Function | MediumTest CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_NE(installResult, "Success"); + EXPECT_NE(installResult, "Success"); sptr bundleCleanCacheCallback = (new (std::nothrow) CleanCacheCallBackImpl()); - ASSERT_NE(bundleCleanCacheCallback, nullptr); + EXPECT_NE(bundleCleanCacheCallback, nullptr); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool cleanCacheResult = bundleMgrProxy->CleanBundleCacheFiles(appName, bundleCleanCacheCallback); EXPECT_FALSE(cleanCacheResult); @@ -3681,13 +3665,13 @@ HWTEST_F(ActsBmsKitSystemTest, GetLaunchWantForBundle_0100, Function | MediumTes CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; Want want; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool launchWantResult = bundleMgrProxy->GetLaunchWantForBundle(appName, want); EXPECT_TRUE(launchWantResult); @@ -3695,7 +3679,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetLaunchWantForBundle_0100, Function | MediumTes resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!launchWantResult) { APP_LOGI("GetLaunchWantForBundle_0100 failed - cycle count: %{public}d", i); @@ -3730,13 +3714,13 @@ HWTEST_F(ActsBmsKitSystemTest, GetLaunchWantForBundle_0200, Function | MediumTes CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; Want want; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool launchWantResult = bundleMgrProxy->GetLaunchWantForBundle(appName, want); EXPECT_FALSE(launchWantResult); @@ -3744,7 +3728,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetLaunchWantForBundle_0200, Function | MediumTes resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (launchWantResult) { APP_LOGI("GetLaunchWantForBundle_0200 failed - cycle count: %{public}d", i); @@ -3780,7 +3764,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0100, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; Want want; ElementName name; @@ -3792,7 +3776,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0100, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->QueryAbilityInfo(want, abilityInfo); EXPECT_TRUE(queryResult); @@ -3802,7 +3786,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0100, Function | MediumTest | Le resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("QueryAbilityInfo_0100 failed - cycle count: %{public}d", i); @@ -3836,7 +3820,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0200, Function | MediumTest | Le CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; Want want; ElementName name; @@ -3846,7 +3830,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0200, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->QueryAbilityInfo(want, abilityInfo); EXPECT_FALSE(queryResult); @@ -3854,7 +3838,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0200, Function | MediumTest | Le resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (queryResult) { APP_LOGI("QueryAbilityInfo_0200 failed - cycle count: %{public}d", i); @@ -3889,7 +3873,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0300, Function | MediumTest | Le Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; Want want; ElementName name; @@ -3901,7 +3885,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0300, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->QueryAbilityInfo(want, abilityInfo); EXPECT_TRUE(queryResult); @@ -3910,7 +3894,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryAbilityInfo_0300, Function | MediumTest | Le resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("QueryAbilityInfo_0300 failed - cycle count: %{public}d", i); break; @@ -3945,7 +3929,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfosByMetaData_0100, Function | MediumT CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::vector bundleInfos; @@ -3953,7 +3937,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfosByMetaData_0100, Function | MediumT sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getResult = bundleMgrProxy->GetBundleInfosByMetaData(metadata, bundleInfos); EXPECT_TRUE(getResult); @@ -3961,7 +3945,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfosByMetaData_0100, Function | MediumT resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getResult) { APP_LOGI("GetBundleInfosByMetaData_0100 failed - cycle count: %{public}d", i); @@ -3992,7 +3976,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundleInfosByMetaData_0200, Function | MediumT sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getResult = bundleMgrProxy->GetBundleInfosByMetaData(metadata, bundleInfos); EXPECT_FALSE(getResult); @@ -4031,7 +4015,7 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; Want want; ElementName name; @@ -4043,17 +4027,17 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = bundleMgrProxy->QueryAbilityInfo(want, abilityInfo); EXPECT_EQ(abilityInfo.name, abilityName); EXPECT_TRUE(queryResult); std::string path = "/data/test/abilityInfo.txt"; - bool isSuccess = CreateFile(path); - ASSERT_TRUE(isSuccess); + std::ofstream file(path); + file.close(); int fd = open(path.c_str(), O_WRONLY | O_CLOEXEC); - ASSERT_NE(fd, -1) << "open file error"; + EXPECT_NE(fd, -1) << "open file error"; std::string prefix = "[ability]"; abilityInfo.Dump(prefix, fd); long length = lseek(fd, 0, SEEK_END); @@ -4063,7 +4047,7 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("AbilityDump_0100 failed - cycle count: %{public}d", i); @@ -4099,14 +4083,14 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfoDump_0100, Function | MediumTest | CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetApplicationInfo(appName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); @@ -4114,10 +4098,10 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfoDump_0100, Function | MediumTest | EXPECT_EQ(appInfo.name, appName); std::string path = "/data/test/appInfo.txt"; - bool isSuccess = CreateFile(path); - ASSERT_TRUE(isSuccess); + std::ofstream file(path); + file.close(); int fd = open(path.c_str(), O_WRONLY | O_CLOEXEC); - ASSERT_NE(fd, -1) << "open file error"; + EXPECT_NE(fd, -1) << "open file error"; std::string prefix = "[appInfo]"; appInfo.Dump(prefix, fd); long length = lseek(fd, 0, SEEK_END); @@ -4127,7 +4111,7 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfoDump_0100, Function | MediumTest | resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!getInfoResult) { APP_LOGI("ApplicationInfoDump_0100 failed - cycle count: %{public}d", i); @@ -4163,7 +4147,7 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0100, Function | MediumTest | Level1) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); Install(bundleFilePath, InstallFlag::NORMAL, resvec); @@ -4173,7 +4157,7 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0100, Function | MediumTest | Level1) std::vector resvec2; Uninstall(appName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (std::strcmp(installResult.c_str(), "Success") == 0) { APP_LOGI("Errors_0100 failed - cycle count: %{public}d", i); @@ -4207,18 +4191,18 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0200, Function | MediumTest | Level1) Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; Install(bundleFilePath, InstallFlag::REPLACE_EXISTING, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Failure[ERR_INSTALL_VERSION_DOWNGRADE]"); + EXPECT_EQ(installResult, "Failure[ERR_INSTALL_VERSION_DOWNGRADE]"); std::vector resvec2; Uninstall(bundleName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (std::strcmp(installResult.c_str(), "Success") == 0) { APP_LOGI("Errors_0200 failed - cycle count: %{public}d", i); @@ -4251,12 +4235,12 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0300, Function | MediumTest | Level1) Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); + EXPECT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); resvec.clear(); Install(bundleFilePath, InstallFlag::REPLACE_EXISTING, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); + EXPECT_EQ(installResult, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); std::string bundleName = BASE_BUNDLE_NAME + "14"; @@ -4264,7 +4248,7 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0300, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -4368,7 +4352,7 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0600, Function | MediumTest | Level1) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Failure[MSG_ERR_INSTALL_FILE_PATH_INVALID]"); + EXPECT_EQ(installResult, "Failure[MSG_ERR_INSTALL_FILE_PATH_INVALID]"); if (std::strcmp(installResult.c_str(), "Success") == 0) { APP_LOGI("Errors_0600 failed - cycle count: %{public}d", i); break; @@ -4404,19 +4388,19 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0700, Function | MediumTest | Level1) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); appName = BASE_BUNDLE_NAME + "1"; Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; std::vector resvec2; appName = BASE_BUNDLE_NAME + "e"; Uninstall(appName, resvec2); uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Failure[ERR_UNINSTALL_MISSING_INSTALLED_BUNDLE]"); + EXPECT_EQ(uninstallResult, "Failure[ERR_UNINSTALL_MISSING_INSTALLED_BUNDLE]"); if (std::strcmp(uninstallResult.c_str(), "Success") == 0) { APP_LOGI("Errors_0700 failed - cycle count: %{public}d", i); @@ -4453,17 +4437,17 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0800, Function | MediumTest | Level1) CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; resvec.clear(); Uninstall(appName, resvec); uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Failure[ERR_UNINSTALL_MISSING_INSTALLED_BUNDLE]"); + EXPECT_EQ(uninstallResult, "Failure[ERR_UNINSTALL_MISSING_INSTALLED_BUNDLE]"); if (std::strcmp(uninstallResult.c_str(), "Success") == 0) { APP_LOGI("Errors_0800 failed - cycle count: %{public}d", i); break; @@ -4496,7 +4480,7 @@ HWTEST_F(ActsBmsKitSystemTest, Errors_0900, Function | MediumTest | Level1) Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Failure[MSG_ERR_UNINSTALL_SYSTEM_APP_ERROR]"); + EXPECT_EQ(uninstallResult, "Failure[MSG_ERR_UNINSTALL_SYSTEM_APP_ERROR]"); if (std::strcmp(uninstallResult.c_str(), "Success") == 0) { APP_LOGI("Errors_0900 failed - cycle count: %{public}d", i); break; @@ -4531,14 +4515,14 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetApplicationInfo(appName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); @@ -4546,10 +4530,10 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev EXPECT_EQ(appInfo.name, appName); ApplicationInfo *pAppInfo = &appInfo; std::string path = "/data/test/pAppInfo_01.txt"; - bool isSuccess = CreateFile(path); - ASSERT_TRUE(isSuccess); + std::ofstream file(path); + file.close(); int fd = open(path.c_str(), O_RDWR); - ASSERT_NE(fd, -1) << "open file error"; + EXPECT_NE(fd, -1) << "open file error"; std::string prefix = "[pAppInfo]"; pAppInfo->Dump(prefix, fd); long length = lseek(fd, 0, SEEK_END); @@ -4566,7 +4550,7 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (retVal <= 0) { APP_LOGI("ApplicationInfo_0100 failed - cycle count: %{public}d", i); @@ -4602,10 +4586,10 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0200, Function | MediumTest | Lev ApplicationInfo *pAppInfo = &appInfo; std::string path = "/data/test/pAppInfo_02.txt"; - bool isSuccess = CreateFile(path); - ASSERT_TRUE(isSuccess); + std::ofstream file(path); + file.close(); int fd = open(path.c_str(), O_RDWR | O_CLOEXEC); - ASSERT_NE(fd, -1) << "open file error"; + EXPECT_NE(fd, -1) << "open file error"; std::string prefix = "[pAppInfo]"; pAppInfo->Dump(prefix, fd); long length = lseek(fd, 0, SEEK_END); @@ -4650,12 +4634,12 @@ HWTEST_F(ActsBmsKitSystemTest, QueryKeepAliveBundleInfos_0100, Function | Medium CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGI("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector bundleInfos; @@ -4665,7 +4649,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryKeepAliveBundleInfos_0100, Function | Medium resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; std::cout << "END QueryKeepAliveBundleInfos_0100" << std::endl; } @@ -4686,12 +4670,12 @@ HWTEST_F(ActsBmsKitSystemTest, QueryKeepAliveBundleInfos_0200, Function | Medium CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGI("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector bundleInfos; @@ -4701,7 +4685,7 @@ HWTEST_F(ActsBmsKitSystemTest, QueryKeepAliveBundleInfos_0200, Function | Medium resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; std::cout << "END QueryKeepAliveBundleInfos_0100" << std::endl; } @@ -4720,24 +4704,24 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0100, Function | MediumTest | sptr installerProxy = GetInstallerProxy(); if (!installerProxy) { APP_LOGE("get bundle installer failed."); - ASSERT_EQ(installerProxy, nullptr); + EXPECT_EQ(installerProxy, nullptr); } InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = false; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string appName = BASE_BUNDLE_NAME + "1"; std::vector resvec; Uninstall(appName, resvec); CommonTool commonTool; std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; CheckFileNonExist(appName); std::cout << "END Uninstall_KeepData_0100" << std::endl; } @@ -4757,24 +4741,24 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0200, Function | MediumTest | sptr installerProxy = GetInstallerProxy(); if (!installerProxy) { APP_LOGE("get bundle installer failed."); - ASSERT_EQ(installerProxy, nullptr); + EXPECT_EQ(installerProxy, nullptr); } InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = true; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string appName = BASE_BUNDLE_NAME + "1"; std::vector resvec; Uninstall(appName, resvec); CommonTool commonTool; std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; CheckFileExist(appName); std::cout << "END Uninstall_KeepData_0200" << std::endl; } @@ -4794,24 +4778,24 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0300, Function | MediumTest | sptr installerProxy = GetInstallerProxy(); if (!installerProxy) { APP_LOGE("get bundle installer failed."); - ASSERT_EQ(installerProxy, nullptr); + EXPECT_EQ(installerProxy, nullptr); } InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = false; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; sptr statusReceiver2 = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver2, nullptr); + EXPECT_NE(statusReceiver2, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver2); installMsg = statusReceiver2->GetResultMsg(); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string appName = BASE_BUNDLE_NAME + "1"; @@ -4821,12 +4805,12 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0300, Function | MediumTest | HapUninstall(bundleName, modulePackage, resvec); CommonTool commonTool; std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall hap fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall hap fail!"; CheckFileNonExist(appName, modulePackage); resvec.clear(); Uninstall(appName, resvec); uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; std::cout << "END Uninstall_KeepData_0300" << std::endl; } @@ -4845,24 +4829,24 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0400, Function | MediumTest | sptr installerProxy = GetInstallerProxy(); if (!installerProxy) { APP_LOGE("get bundle installer failed."); - ASSERT_EQ(installerProxy, nullptr); + EXPECT_EQ(installerProxy, nullptr); } InstallParam installParam; installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = true; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; sptr statusReceiver2 = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver2, nullptr); + EXPECT_NE(statusReceiver2, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver2); installMsg = statusReceiver2->GetResultMsg(); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string appName = BASE_BUNDLE_NAME + "1"; std::vector resvec; @@ -4871,12 +4855,12 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0400, Function | MediumTest | HapUninstall(bundleName, modulePackage, resvec); CommonTool commonTool; std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall hap fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall hap fail!"; CheckFileExist(appName, modulePackage); resvec.clear(); Uninstall(appName, resvec); uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; std::cout << "END Uninstall_KeepData_0400" << std::endl; } @@ -4895,7 +4879,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0100, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string installResult; CommonTool commonTool; @@ -4925,7 +4909,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0100, Function | MediumTest | Le std::string appName = BASE_BUNDLE_NAME + std::to_string(i); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; } if (!ret) { APP_LOGI("GetBundlesForUid_0100 failed - cycle count: %{public}d", i); @@ -4955,7 +4939,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0200, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector bundleNames; bool ret = bundleMgrProxy->GetBundlesForUid(Constants::INVALID_UID, bundleNames); @@ -4986,7 +4970,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0300, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appName = SYSTEM_SETTINGS_BUNDLE_NAME; BundleInfo bundleInfo; @@ -5040,12 +5024,12 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0100, Function | MediumTest | Level std::string name2; Install(bundleFilePath1, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo1; @@ -5055,16 +5039,16 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0100, Function | MediumTest | Level EXPECT_TRUE(ret); Uninstall(appName1, resvec); - ASSERT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; resvec.clear(); Install(bundleFilePath2, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); Install(bundleFilePath1, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; BundleInfo bundleInfo2; bundleMgrProxy->GetBundleInfo(appName1, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo2); @@ -5078,7 +5062,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0100, Function | MediumTest | Level std::vector resvec2; Uninstall(appName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; } if (!ret) { APP_LOGI("GetNameForUid_0100 failed - cycle count: %{public}d", i); @@ -5113,11 +5097,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0200, Function | MediumTest | Level std::string appName = BASE_BUNDLE_NAME + '1'; Install(bundleFilePath, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -5126,7 +5110,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0200, Function | MediumTest | Level EXPECT_FALSE(ret); resvec.clear(); Uninstall(appName, resvec); - ASSERT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; + EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; if (ret) { APP_LOGI("GetNameForUid_0200 failed - cycle count: %{public}d", i); break; @@ -5154,7 +5138,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0300, Function | MediumTest | Level sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appName = SYSTEM_SETTINGS_BUNDLE_NAME; BundleInfo bundleInfo; @@ -5198,18 +5182,18 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityIcon_0100, Function | MediumTest | Leve CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string icon = bundleMgrProxy->GetAbilityIcon(appName, abilityName); EXPECT_EQ(icon, "$media:snowball"); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (icon.compare("$media:snowball") != 0) { APP_LOGI("GetAbilityIcon_0100 failed - cycle count: %{public}d", i); break; @@ -5241,7 +5225,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityIcon_0200, Function | MediumTest | Leve sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string icon = bundleMgrProxy->GetAbilityIcon(appName, abilityName); EXPECT_EQ(icon, "$media:icon"); @@ -5277,19 +5261,19 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityIcon_0300, Function | MediumTest | Leve CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); std::string appName2 = BASE_BUNDLE_NAME + "2"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string icon = bundleMgrProxy->GetAbilityIcon(appName2, abilityName); EXPECT_EQ(icon, Constants::EMPTY_STRING); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (icon.compare(Constants::EMPTY_STRING) != 0) { APP_LOGI("GetAbilityIcon_0300 failed - cycle count: %{public}d", i); break; @@ -5323,18 +5307,18 @@ HWTEST_F(ActsBmsKitSystemTest, GetAbilityIcon_0400, Function | MediumTest | Leve CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string icon = bundleMgrProxy->GetAbilityIcon(appName, abilityName); EXPECT_EQ(icon, Constants::EMPTY_STRING); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (icon.compare(Constants::EMPTY_STRING) != 0) { APP_LOGI("GetAbilityIcon_0400 failed - cycle count: %{public}d", i); break; @@ -5367,12 +5351,12 @@ HWTEST_F(ActsBmsKitSystemTest, SetAbilityEnabled_0100, Function | MediumTest | L Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); EXPECT_TRUE(ret); @@ -5383,7 +5367,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetAbilityEnabled_0100, Function | MediumTest | L resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!ret) { APP_LOGI("SetAbilityEnabled_0100 failed - cycle count: %{public}d", i); @@ -5418,14 +5402,14 @@ HWTEST_F(ActsBmsKitSystemTest, SetAbilityEnabled_0200, Function | MediumTest | L Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = BASE_BUNDLE_NAME + "2"; abilityInfo.name = "bmsThirdBundle_A1"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->SetAbilityEnabled(abilityInfo, false); EXPECT_FALSE(ret); @@ -5434,7 +5418,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetAbilityEnabled_0200, Function | MediumTest | L resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (ret) { APP_LOGI("SetAbilityEnabled_0200 failed - cycle count: %{public}d", i); break; @@ -5463,7 +5447,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetAbilityEnabled_0300, Function | MediumTest | L sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } AbilityInfo abilityInfo; abilityInfo.bundleName = appName; @@ -5507,12 +5491,12 @@ HWTEST_F(ActsBmsKitSystemTest, IsAbilityEnabled_0100, Function | MediumTest | Le Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); EXPECT_TRUE(ret); @@ -5523,7 +5507,7 @@ HWTEST_F(ActsBmsKitSystemTest, IsAbilityEnabled_0100, Function | MediumTest | Le resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!ret) { APP_LOGI("IsAbilityEnabled_0100 failed - cycle count: %{public}d", i); break; @@ -5556,21 +5540,21 @@ HWTEST_F(ActsBmsKitSystemTest, IsAbilityEnabled_0200, Function | MediumTest | Le Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; AbilityInfo abilityInfo; abilityInfo.bundleName = BASE_BUNDLE_NAME + "1"; abilityInfo.name = "bmsThirdBundle_A3"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->IsAbilityEnabled(abilityInfo); EXPECT_FALSE(ret); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (ret) { APP_LOGI("IsAbilityEnabled_0200 failed - cycle count: %{public}d", i); @@ -5601,7 +5585,7 @@ HWTEST_F(ActsBmsKitSystemTest, IsAbilityEnabled_0300, Function | MediumTest | Le sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } AbilityInfo abilityInfo; abilityInfo.bundleName = appName; @@ -5648,7 +5632,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetApplicationEnabled_0100, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->SetApplicationEnabled(appName, false); EXPECT_TRUE(ret); @@ -5659,7 +5643,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetApplicationEnabled_0100, Function | MediumTest std::string appName = BASE_BUNDLE_NAME + std::to_string(i); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; } if (!ret) { APP_LOGI("SetApplicationEnabled_0100 failed - cycle count: %{public}d", i); @@ -5698,7 +5682,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetApplicationEnabled_0200, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string bundleName = BASE_BUNDLE_NAME + "2"; bool ret = bundleMgrProxy->SetApplicationEnabled(bundleName, false); @@ -5707,7 +5691,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetApplicationEnabled_0200, Function | MediumTest EXPECT_FALSE(ret); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (ret) { APP_LOGI("SetApplicationEnabled_0200 failed - cycle count: %{public}d", i); break; @@ -5735,7 +5719,7 @@ HWTEST_F(ActsBmsKitSystemTest, SetApplicationEnabled_0300, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->SetApplicationEnabled(SYSTEM_SETTINGS_BUNDLE_NAME, false); EXPECT_TRUE(ret); @@ -5775,18 +5759,18 @@ HWTEST_F(ActsBmsKitSystemTest, IsApplicationEnabled_0100, Function | MediumTest Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->IsApplicationEnabled(appName); EXPECT_TRUE(ret); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!ret) { APP_LOGI("IsApplicationEnabled_0100 failed - cycle count: %{public}d", i); break; @@ -5819,19 +5803,19 @@ HWTEST_F(ActsBmsKitSystemTest, IsApplicationEnabled_0200, Function | MediumTest Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string appName2 = BASE_BUNDLE_NAME + "2"; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->IsApplicationEnabled(appName2); EXPECT_FALSE(ret); resvec.clear(); Uninstall(appName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (ret) { APP_LOGI("IsApplicationEnabled_0200 failed - cycle count: %{public}d", i); break; @@ -5859,7 +5843,7 @@ HWTEST_F(ActsBmsKitSystemTest, IsApplicationEnabled_0300, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool ret = bundleMgrProxy->IsApplicationEnabled(SYSTEM_SETTINGS_BUNDLE_NAME); EXPECT_TRUE(ret); diff --git a/test/systemtest/common/bms/bms_install_system_test/BUILD.gn b/test/systemtest/common/bms/bms_install_system_test/BUILD.gn index a7b274ab64ff155bebe339a830fce4d33a888fd2..0aba582287f31e2a6caeb6dc1cbf27989fd2e9a6 100755 --- a/test/systemtest/common/bms/bms_install_system_test/BUILD.gn +++ b/test/systemtest/common/bms/bms_install_system_test/BUILD.gn @@ -49,5 +49,5 @@ ohos_systemtest("BmsInstallSystemTest") { group("systemtest") { testonly = true - deps = [] + deps = [ ":BmsInstallSystemTest" ] } diff --git a/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp b/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp index 6fdce038c8448d4e90338a7865f91a4ded341f7e..b018a324f714d7dc0d19c17b3f7680aa08257bc7 100755 --- a/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp +++ b/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp @@ -199,9 +199,9 @@ void BmsInstallSystemTest::InstallBundle( installParam.userId = userId; } sptr statusReceiver(new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); bool installResult = installerProxy->Install(bundleFilePath, installParam, statusReceiver); - ASSERT_TRUE(installResult); + EXPECT_TRUE(installResult); installMsg = statusReceiver->GetResultMsg(); } @@ -215,9 +215,9 @@ void BmsInstallSystemTest::InstallMultiBundle(const std::string bundleFilePath, InstallParam installParam; installParam.installFlag = (InstallFlag)installFlag; sptr statusReceiver(new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); bool installResult = installerProxy->Install(bundleFilePath, installParam, statusReceiver); - ASSERT_TRUE(installResult); + EXPECT_TRUE(installResult); APP_LOGI("Install MSG: %{public}s", statusReceiver->GetResultMsg().c_str()); } @@ -232,13 +232,13 @@ void BmsInstallSystemTest::UninstallBundle( } sptr statusReceiver(new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); InstallParam installParam; if (userId != 0) { installParam.userId = userId; } bool uninstallResult = installerProxy->Uninstall(bundleName, installParam, statusReceiver); - ASSERT_TRUE(uninstallResult); + EXPECT_TRUE(uninstallResult); uninstallMsg = statusReceiver->GetResultMsg(); } @@ -255,10 +255,10 @@ void BmsInstallSystemTest::CheckBundleInfo(const std::string &version, const std sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool isGetInfoSuccess = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_TRUE(isGetInfoSuccess); + EXPECT_TRUE(isGetInfoSuccess); EXPECT_EQ(bundleInfo.name, bundleName); EXPECT_EQ(bundleInfo.versionName, version); } @@ -299,7 +299,7 @@ void BmsInstallSystemTest::CheckInstallIsSuccess( void BmsInstallSystemTest::CheckFileNonExist(const std::string &bundleName) const { int bundleDataExist = access((DATA_ROOT_PATH + bundleName).c_str(), F_OK); - ASSERT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << bundleName; + EXPECT_NE(bundleDataExist, 0) << "the bundle data dir exists: " << bundleName; int codeExist = access((CODE_ROOT_PATH + bundleName).c_str(), F_OK); EXPECT_NE(codeExist, 0) << "the bundle code dir exists: " << bundleName; } @@ -341,7 +341,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0100, Function | MediumTest | Level1) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -352,7 +352,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0100, Function | MediumTest | Level1) std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_0100" << std::endl; } @@ -372,7 +372,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0200, Function | MediumTest | Level2) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; CheckInstallIsSuccess(bundleName, modulePackage, abilityNames); @@ -388,7 +388,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0200, Function | MediumTest | Level2) std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_0200" << std::endl; } @@ -421,7 +421,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0300, Function | MediumTest | Level1) std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success"); + EXPECT_EQ(uninstallMsg, "Success"); } std::cout << "END BMS_Install_0300" << std::endl; } @@ -439,7 +439,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0400, Function | MediumTest | Level1) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle13.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "5"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -453,7 +453,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0400, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGI("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfosResult = bundleMgrProxy->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos); EXPECT_TRUE(getInfosResult); @@ -468,7 +468,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0400, Function | MediumTest | Level1) EXPECT_TRUE(isSubStrExist); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_0400" << std::endl; } @@ -487,7 +487,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0500, Function | MediumTest | Level2) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; @@ -496,12 +496,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0500, Function | MediumTest | Level2) bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; InstallBundle(bundleFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_VERSION_DOWNGRADE]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_VERSION_DOWNGRADE]"); CheckInstallIsSuccess(bundleName, modulePackage, abilityNames); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_0500" << std::endl; } @@ -520,7 +520,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0600, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; @@ -530,7 +530,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0600, Function | MediumTest | Level1) std::string bundleReFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle9.hap"; std::this_thread::sleep_for(50ms); InstallBundle(bundleReFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; CheckInstallIsSuccess(bundleName, modulePackage, abilityNames); @@ -538,7 +538,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0600, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_0600" << std::endl; } @@ -561,7 +561,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0700, Function | MediumTest | Level2) int32_t size = bundlePaths.size(); for (int i = 0; i < size; i++) { InstallBundle(bundlePaths[i], InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, errorCodes[i]); + EXPECT_EQ(installMsg, errorCodes[i]); CheckFileNonExist(bundleNames[i]); } @@ -569,7 +569,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0700, Function | MediumTest | Level2) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bundleMgrProxy->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos); @@ -599,9 +599,9 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0800, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle14.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); InstallBundle(bundleFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_MISSING_PROP]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "14"; @@ -609,7 +609,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0800, Function | MediumTest | Level2) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -628,10 +628,10 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_0900, Function | MediumTest | Level2) std::string installMsg; std::string bundleFilePath = THIRD_BUNDLE_PATH + "notexist.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[MSG_ERR_INSTALL_FILE_PATH_INVALID]"); + EXPECT_EQ(installMsg, "Failure[MSG_ERR_INSTALL_FILE_PATH_INVALID]"); InstallBundle(bundleFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Failure[MSG_ERR_INSTALL_FILE_PATH_INVALID]"); + EXPECT_EQ(installMsg, "Failure[MSG_ERR_INSTALL_FILE_PATH_INVALID]"); std::cout << "END BMS_Install_0900" << std::endl; } @@ -648,7 +648,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1000, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundleNoSign.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_NO_SIGNATURE_INFO]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_NO_SIGNATURE_INFO]"); std::string bundleName = "com.third.hiworld.example1"; CheckFileNonExist(bundleName); @@ -670,7 +670,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1100, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; std::vector hap2AbilityNames = {"bmsThirdBundle_A1", "bmsThirdBundle_A2"}; @@ -679,7 +679,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1100, Function | MediumTest | Level1) bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; std::vector hap1AbilityNames = {"bmsThirdBundle_A1"}; @@ -689,7 +689,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1100, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1100" << std::endl; } @@ -708,7 +708,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1200, Function | MediumTest | Level1) InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -719,7 +719,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1200, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1200" << std::endl; } @@ -738,7 +738,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1300, Function | MediumTest | Level1) InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -749,7 +749,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1300, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1300" << std::endl; } @@ -768,7 +768,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1400, Function | MediumTest | Level1) InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -779,7 +779,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1400, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1400" << std::endl; } @@ -797,12 +797,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1500, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle42.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -813,7 +813,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1500, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1500" << std::endl; } @@ -832,12 +832,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1600, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -852,7 +852,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1600, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1600" << std::endl; } @@ -871,12 +871,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1700, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle5.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -891,7 +891,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1700, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1700" << std::endl; } @@ -910,12 +910,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1800, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle42.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -923,7 +923,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1800, Function | MediumTest | Level1) CheckInstallIsSuccess(bundleName, modulePackage, hap1AbilityNames); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1800" << std::endl; } @@ -941,12 +941,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1900, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -961,7 +961,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_1900, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_1900" << std::endl; } @@ -980,12 +980,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2000, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle5.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1000,7 +1000,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2000, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_2000" << std::endl; } @@ -1019,12 +1019,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2100, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[MSG_ERR_INSTALL_ENTRY_ALREADY_EXIST]"); + EXPECT_EQ(installMsg, "Failure[MSG_ERR_INSTALL_ENTRY_ALREADY_EXIST]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1035,7 +1035,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2100, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "START BMS_Install_2100" << std::endl; } @@ -1054,12 +1054,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2200, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1074,7 +1074,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2200, Function | MediumTest | Level1) CheckBundleInfo(version, bundleName); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "START BMS_Install_2200" << std::endl; } @@ -1092,12 +1092,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2300, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle5.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1113,7 +1113,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2300, Function | MediumTest | Level1) std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Install_2300" << std::endl; } @@ -1131,14 +1131,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2400, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e23.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1157,7 +1157,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2500, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1168,7 +1168,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2500, Function | MediumTest | Level2) std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "e14.hap"; InstallBundle(bundleFilePath2, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); @@ -1189,14 +1189,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2600, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e22.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1215,7 +1215,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2700, Function | MediumTest | Level1) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle41.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1227,7 +1227,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2700, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; @@ -1268,14 +1268,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2800, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e3.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1296,14 +1296,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_2900, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e21.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1324,17 +1324,17 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3000, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e14.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_FALSE(getInfoResult); + EXPECT_FALSE(getInfoResult); std::cout << "END BMS_Install_3000" << std::endl; } @@ -1352,14 +1352,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3100, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e12.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1380,7 +1380,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3200, Function | MediumTest | Level1) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1391,7 +1391,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3200, Function | MediumTest | Level1) bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName2 = THIRD_BASE_BUNDLE_NAME + "2"; modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; @@ -1425,7 +1425,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3300, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundles1.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_ALREADY_EXIST]") << "Success!" << bundleFilePath; + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_ALREADY_EXIST]") << "Success!" << bundleFilePath; std::cout << "END BMS_Install_3300" << std::endl; } @@ -1443,14 +1443,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3400, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e4.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_TYPE_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_TYPE_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1471,14 +1471,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3500, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e5.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_PROFILE_PROP_CHECK_ERROR]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1499,14 +1499,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_Install_3600, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "e6.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_BAD_PROFILE]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_BAD_PROFILE]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); @@ -1525,7 +1525,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_InstallProgressInfo_0100, Function | MediumTe std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -1575,7 +1575,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_MultiHapInstall_0100, Function | MediumTest | sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfosResult = bundleMgrProxy->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos); EXPECT_TRUE(getInfosResult); @@ -1718,7 +1718,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_SystemAppInstall_0300, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector bundleInfos; @@ -1765,7 +1765,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0100, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; @@ -1775,7 +1775,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0100, Function | MediumTest | Level1) std::this_thread::sleep_for(50ms); bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle9.hap"; InstallBundle(bundleFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string version = "3.0"; hap1AbilityNames = {"bmsThirdBundle_A1"}; @@ -1802,7 +1802,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0200, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; @@ -1812,7 +1812,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0200, Function | MediumTest | Level1) std::this_thread::sleep_for(50ms); bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle10.hap"; InstallBundle(bundleFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string version = "1.0"; CheckBundleInfo(version, bundleName); @@ -1838,7 +1838,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0300, Function | MediumTest | Level2) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; @@ -1847,7 +1847,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0300, Function | MediumTest | Level2) bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; InstallBundle(bundleFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_VERSION_DOWNGRADE]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_VERSION_DOWNGRADE]"); std::string version = "3.0"; CheckBundleInfo(version, bundleName); @@ -1874,7 +1874,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0400, Function | MediumTest | Level1) std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h2"; @@ -1888,7 +1888,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_Upgrade_0400, Function | MediumTest | Level1) std::this_thread::sleep_for(50ms); bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle9.hap"; InstallBundle(bundleFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); CheckInstallIsSuccess(bundleName, modulePackage, hap1AbilityNames); std::string uninstallMsg; @@ -1994,7 +1994,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_BundleDataStorage_0100, Function | MediumTest InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -2004,7 +2004,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_BundleDataStorage_0100, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; bool isGetInfoSuccess = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -2038,14 +2038,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_BundleDataStorage_0200, Function | MediumTest sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string installMsg; std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success"); + EXPECT_EQ(installMsg, "Success"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -2053,7 +2053,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_BundleDataStorage_0200, Function | MediumTest CheckInstallIsSuccess(bundleName, modulePackage, hap1AbilityNames); bool isGetInfoSuccess = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_TRUE(isGetInfoSuccess); + EXPECT_TRUE(isGetInfoSuccess); EXPECT_EQ(bundleInfo.name, "com.third.hiworld.example1"); EXPECT_EQ(bundleInfo.vendor, "example"); @@ -2066,7 +2066,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_BundleDataStorage_0200, Function | MediumTest bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle11.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_NO_PROFILE]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_PARSE_NO_PROFILE]"); std::string eBundleName = THIRD_BASE_BUNDLE_NAME + "11"; CheckFileNonExist(eBundleName); @@ -2095,22 +2095,22 @@ HWTEST_F(BmsInstallSystemTest, BMS_Broadcasting_0100, Function | MediumTest | Le CommonEventSubscribeInfo subscriberInfo(matchingSkillsObj); std::shared_ptr subScriber = std::make_shared(subscriberInfo); bool isSubscribeSuccess = CommonEventManager::SubscribeCommonEvent(subScriber); - ASSERT_TRUE(isSubscribeSuccess); + EXPECT_TRUE(isSubscribeSuccess); std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string subScriberResult = subScriber->GetSubscriberResultMsg(); EXPECT_EQ(subScriberResult, CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); bool isUnSubscribeSuccess = CommonEventManager::UnSubscribeCommonEvent(subScriber); - ASSERT_TRUE(isUnSubscribeSuccess); + EXPECT_TRUE(isUnSubscribeSuccess); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; std::cout << "END BMS_Broadcasting_0100" << std::endl; } @@ -2129,26 +2129,26 @@ HWTEST_F(BmsInstallSystemTest, BMS_Broadcasting_0200, Function | MediumTest | Le CommonEventSubscribeInfo subScriberInfo(matchingSkillsObj); std::shared_ptr subScriber = std::make_shared(subScriberInfo); bool isSubscribeSuccess = CommonEventManager::SubscribeCommonEvent(subScriber); - ASSERT_TRUE(isSubscribeSuccess); + EXPECT_TRUE(isSubscribeSuccess); std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string bundleReFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle9.hap"; std::this_thread::sleep_for(50ms); InstallBundle(bundleReFilePath, InstallFlag::REPLACE_EXISTING, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string subScriberResult = subScriber->GetSubscriberResultMsg(); EXPECT_EQ(subScriberResult, CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; bool isUnSubscribeSuccess = CommonEventManager::UnSubscribeCommonEvent(subScriber); - ASSERT_TRUE(isUnSubscribeSuccess); + EXPECT_TRUE(isUnSubscribeSuccess); std::cout << "END BMS_Broadcasting_0200" << std::endl; } @@ -2167,21 +2167,21 @@ HWTEST_F(BmsInstallSystemTest, BMS_Broadcasting_0300, Function | MediumTest | Le CommonEventSubscribeInfo subscriberInfo(matchingSkillsObj); std::shared_ptr subScriber = std::make_shared(subscriberInfo); bool isSubscribeSuccess = CommonEventManager::SubscribeCommonEvent(subScriber); - ASSERT_TRUE(isSubscribeSuccess); + EXPECT_TRUE(isSubscribeSuccess); std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!"; + EXPECT_EQ(installMsg, "Success") << "install fail!"; std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; std::string subScriberResult = subScriber->GetSubscriberResultMsg(); EXPECT_EQ(subScriberResult, CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); bool isUnSubscribeSuccess = CommonEventManager::UnSubscribeCommonEvent(subScriber); - ASSERT_TRUE(isUnSubscribeSuccess); + EXPECT_TRUE(isUnSubscribeSuccess); std::cout << "END BMS_Broadcasting_0300" << std::endl; } @@ -2203,15 +2203,15 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0100, Function | MediumTest | Leve sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundlePermission1.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundlePermission2.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = "com.third.hiworld.example2"; std::string modulePackage = "com.third.hiworld.example.h2"; @@ -2220,12 +2220,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0100, Function | MediumTest | Leve std::string bundleName2 = "com.third.hiworld.example3"; std::string permissionName = "com.example.permission"; bool isGetInfoSuccess = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_TRUE(isGetInfoSuccess); + EXPECT_TRUE(isGetInfoSuccess); EXPECT_EQ(commonTool.VectorToStr(bundleInfo.defPermissions), permissionName); CheckInstallIsSuccess(bundleName2, modulePackage, abilityNames); isGetInfoSuccess = bundleMgrProxy->GetBundleInfo(bundleName2, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_TRUE(isGetInfoSuccess); + EXPECT_TRUE(isGetInfoSuccess); bool ret = bundleMgrProxy->CanRequestPermission(bundleName2, permissionName, userid); EXPECT_TRUE(ret); @@ -2234,9 +2234,9 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0100, Function | MediumTest | Leve std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; UninstallBundle(bundleName2, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; std::cout << "END BMS_Permission_0100" << std::endl; } @@ -2258,15 +2258,15 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0200, Function | MediumTest | Leve sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle8.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = "com.third.hiworld.example2"; std::string modulePackage = "com.third.hiworld.example.h2"; @@ -2275,12 +2275,12 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0200, Function | MediumTest | Leve std::string bundleName2 = "com.third.hiworld.example3"; std::string permissionName = "com.example.permission"; bool isGetInfoSuccess = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_TRUE(isGetInfoSuccess); + EXPECT_TRUE(isGetInfoSuccess); EXPECT_EQ(commonTool.VectorToStr(bundleInfo.defPermissions), permissionName); CheckInstallIsSuccess(bundleName2, modulePackage, abilityNames); isGetInfoSuccess = bundleMgrProxy->GetBundleInfo(bundleName2, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_TRUE(isGetInfoSuccess); + EXPECT_TRUE(isGetInfoSuccess); bool ret = bundleMgrProxy->CanRequestPermission(bundleName2, permissionName, userid); EXPECT_FALSE(ret); ret = bundleMgrProxy->RequestPermissionFromUser(bundleName2, permissionName, userid); @@ -2290,9 +2290,9 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0200, Function | MediumTest | Leve std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; UninstallBundle(bundleName2, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; std::cout << "END BMS_Permission_0200" << std::endl; } @@ -2311,15 +2311,15 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0300, Function | MediumTest | Leve sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundlePermission1.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundlePermission2.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = "com.third.hiworld.example2"; std::string modulePackage = "com.third.hiworld.example.h2"; @@ -2336,9 +2336,9 @@ HWTEST_F(BmsInstallSystemTest, BMS_Permission_0300, Function | MediumTest | Leve std::string uninstallMsg; UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; UninstallBundle(bundleName2, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_Permission_0300" << std::endl; } @@ -2373,7 +2373,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_DFX_0200, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string modulePackage = THIRD_BASE_BUNDLE_NAME + ".h1"; @@ -2384,7 +2384,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_DFX_0200, Function | MediumTest | Level2) UninstallBundle(bundleName, uninstallMsg, Constants::INVALID_USERID); EXPECT_EQ(uninstallMsg, "Failure[ERR_UNINSTALL_PARAM_ERROR]"); UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "install fail!" << bundleFilePath; std::cout << "END BMS_DFX_0200" << std::endl; } @@ -2402,7 +2402,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_DFX_0300, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string installMsg; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath; std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; std::string errBundleName = ""; @@ -2414,7 +2414,7 @@ HWTEST_F(BmsInstallSystemTest, BMS_DFX_0300, Function | MediumTest | Level2) UninstallBundle(errBundleName, uninstallMsg); EXPECT_EQ(uninstallMsg, "Failure[ERR_UNINSTALL_INVALID_NAME]"); UninstallBundle(bundleName, uninstallMsg); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!" << bundleFilePath; std::cout << "END BMS_DFX_0300" << std::endl; } @@ -2432,14 +2432,14 @@ HWTEST_F(BmsInstallSystemTest, BMS_DFX_0400, Function | MediumTest | Level2) std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle43.hap"; InstallBundle(bundleFilePath, InstallFlag::NORMAL, installMsg); - ASSERT_EQ(installMsg, "Failure[ERR_INSTALL_INVALID_HAP_SIZE]"); + EXPECT_EQ(installMsg, "Failure[ERR_INSTALL_INVALID_HAP_SIZE]"); std::string bundleName = THIRD_BASE_BUNDLE_NAME + "big"; BundleInfo bundleInfo; sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoResult); diff --git a/test/systemtest/common/bms/bms_launcher_service_system_test/BUILD.gn b/test/systemtest/common/bms/bms_launcher_service_system_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..c672c8b6a0779bed3929cbfb18b7f2f5b4984f4b --- /dev/null +++ b/test/systemtest/common/bms/bms_launcher_service_system_test/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 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/appexecfwk/standard/appexecfwk.gni") +module_output_path = "appexecfwk_standard/bundlemgrsst" + +ohos_systemtest("BmsLauncherServiceSystemTest") { + module_out_path = module_output_path + + configs = [ "${libs_path}/libeventhandler:libeventhandler_config" ] + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", + "${services_path}/bundlemgr/include", + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "${common_path}:libappexecfwk_common", + "${libs_path}/libeventhandler:libeventhandler_target", + "${services_path}/bundlemgr:libbms", + "${services_path}/test/moduletest/utils:tool_common", + "//base/security/appverify/interfaces/innerkits/appverify:libhapverify", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + sources = [ "bms_launcher_service_system_test.cpp" ] + + defines = [ "APP_LOG_TAG = \"BundleMgrTool\"" ] + + external_deps = [ + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("systemtest") { + testonly = true + + deps = [ ":BmsLauncherServiceSystemTest" ] +} diff --git a/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp b/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e503c647a4f2acc7edbcad098565e32e568b6333 --- /dev/null +++ b/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp @@ -0,0 +1,1301 @@ +/* + * Copyright (c) 2021 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 "app_log_wrapper.h" +#include "bundle_constants.h" +#include "bundle_installer_interface.h" +#include "bundle_mgr_interface.h" +#include "iservice_registry.h" +#include "status_receiver_host.h" +#include "system_ability_definition.h" +#include "operation_builder.h" +#include "common_tool.h" +#include "launcher_ability_info.h" +#include "launcher_service.h" + +namespace { +const std::string THIRD_BUNDLE_PATH = "/data/test/bms_bundle/"; +const std::string THIRD_BASE_BUNDLE_NAME = "com.example.third"; +const std::string SYSTEM_BASE_BUNDLE_NAME = "com.example.system"; +const std::string CAMERA = "ohos.permission.CAMERA"; +const std::string RESOURCE_ROOT_PATH = "/data/test/"; +const std::string MSG_SUCCESS = "[SUCCESS]"; +const std::string OPERATION_FAILED = "Failure"; +const std::string OPERATION_SUCCESS = "Success"; +const std::string BUNDLE_ADD = "Bundle Add Success"; +const std::string BUNDLE_UPDATE = "Bundle Update Success"; +const std::string BUNDLE_REMOVE = "Bundle Remove Success"; +const unsigned TWO = 2; + +} // namespace +using OHOS::AAFwk::Want; +using namespace testing::ext; +using namespace std::chrono_literals; +namespace OHOS { +namespace AppExecFwk { +class StatusReceiverImpl : public StatusReceiverHost { +public: + StatusReceiverImpl(); + virtual ~StatusReceiverImpl(); + virtual void OnStatusNotify(const int progress) override; + virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override; + std::string GetResultMsg() const; + +private: + mutable std::promise resultMsgSignal_; + + DISALLOW_COPY_AND_MOVE(StatusReceiverImpl); +}; +class BmsLauncherServiceSystemTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + static void Install(const std::string &bundleFilePath, const InstallFlag installFlag, std::string &installMessage); + static void Uninstall(const std::string &bundleName, std::string &installMessage); + static sptr GetBundleMgrProxy(); + static sptr GetInstallerProxy(); + static void Complete(const std::string message); + static bool Wait(const std::string message); + +private: + static std::mutex mutex_; + static std::condition_variable cv_; + static std::string message_; +}; +std::string BmsLauncherServiceSystemTest::message_ = ""; +std::condition_variable BmsLauncherServiceSystemTest::cv_ = std::condition_variable(); +std::mutex BmsLauncherServiceSystemTest::mutex_ = std::mutex(); +void BmsLauncherServiceSystemTest::Complete(const std::string message) +{ + std::this_thread::sleep_for(500ms); + std::unique_lock lock(mutex_); + if (message_.empty()) { + GTEST_LOG_(INFO) << "Message empty."; + message_ = message; + return; + } + if (message_.compare(message) == 0) { + GTEST_LOG_(INFO) << "Complete."; + cv_.notify_all(); + message_ = ""; + return; + } + GTEST_LOG_(INFO) << "Can't Complete." << message_; + return; +} + +bool BmsLauncherServiceSystemTest::Wait(const std::string message) +{ + GTEST_LOG_(INFO) << "Wait start."; + std::unique_lock lock(mutex_); + if (!message_.empty()) { + GTEST_LOG_(INFO) << "Message is not empty." << message_; + bool ret = (message_ == message); + message_ = ""; + return ret; + } + message_ = message; + if (cv_.wait_for(lock, std::chrono::seconds(5)) == std::cv_status::timeout) { + GTEST_LOG_(INFO) << "Time out."; + message_ = ""; + return false; + } + GTEST_LOG_(INFO) << "Wait done."; + return true; +} + +sptr BmsLauncherServiceSystemTest::GetBundleMgrProxy() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + APP_LOGE("fail to get system ability mgr."); + return nullptr; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + APP_LOGE("fail to get bundle manager proxy."); + return nullptr; + } + + APP_LOGI("get bundle manager proxy success."); + return iface_cast(remoteObject); +} + +sptr BmsLauncherServiceSystemTest::GetInstallerProxy() +{ + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + APP_LOGE("bundle mgr proxy is nullptr."); + return nullptr; + } + + sptr installerProxy = bundleMgrProxy->GetBundleInstaller(); + if (!installerProxy) { + APP_LOGE("fail to get bundle installer proxy"); + return nullptr; + } + + APP_LOGI("get bundle installer proxy success."); + return installerProxy; +} + +void BmsLauncherServiceSystemTest::Install( + const std::string &bundleFilePath, const InstallFlag installFlag, std::string &installMessage) +{ + sptr installerProxy = GetInstallerProxy(); + if (!installerProxy) { + APP_LOGE("get bundle installer failed."); + installMessage = OPERATION_FAILED; + return; + } + InstallParam installParam; + installParam.installFlag = installFlag; + installParam.userId = Constants::DEFAULT_USERID; + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + EXPECT_NE(statusReceiver, nullptr); + installerProxy->Install(bundleFilePath, installParam, statusReceiver); + installMessage = statusReceiver->GetResultMsg(); +} + +void BmsLauncherServiceSystemTest::Uninstall(const std::string &bundleName, std::string &uninstallMessage) +{ + sptr installerProxy = GetInstallerProxy(); + if (!installerProxy) { + APP_LOGE("get bundle installer failed."); + uninstallMessage = OPERATION_FAILED; + return; + } + + if (bundleName.empty()) { + APP_LOGE("bundelname is null."); + uninstallMessage = OPERATION_FAILED; + } else { + InstallParam installParam; + installParam.userId = Constants::DEFAULT_USERID; + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); + EXPECT_NE(statusReceiver, nullptr); + installerProxy->Uninstall(bundleName, installParam, statusReceiver); + uninstallMessage = statusReceiver->GetResultMsg(); + } +} + +void BmsLauncherServiceSystemTest::SetUpTestCase() +{} +void BmsLauncherServiceSystemTest::TearDownTestCase() +{} +void BmsLauncherServiceSystemTest::SetUp() +{} +void BmsLauncherServiceSystemTest::TearDown() +{} + +class TestBundleStatusCallback : public IBundleStatusCallback { +public: + TestBundleStatusCallback() = default; + ~TestBundleStatusCallback() = default; + virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, + const std::string &bundleName) override; + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override; + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override; + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override; + virtual sptr AsObject() override; +}; + +void TestBundleStatusCallback::OnBundleStateChanged( + const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) +{ + GTEST_LOG_(INFO) << "OnBundleStateChanged " << resultMsg << " bundle name is " << bundleName; +} +void TestBundleStatusCallback::OnBundleAdded(const std::string &bundleName, const int userId) +{ + GTEST_LOG_(INFO) << "OnBundleAdded bundle name " << bundleName << "is exist"; + GTEST_LOG_(INFO) << "bundle name is " << bundleName << "is exist"; + BmsLauncherServiceSystemTest::Complete(BUNDLE_ADD); +} + +void TestBundleStatusCallback::OnBundleUpdated(const std::string &bundleName, const int userId) +{ + GTEST_LOG_(INFO) << "OnBundleUpdated bundle name " << bundleName << "is exist"; + GTEST_LOG_(INFO) << "bundle name is " << bundleName << "is exist"; + BmsLauncherServiceSystemTest::Complete(BUNDLE_UPDATE); +} + +void TestBundleStatusCallback::OnBundleRemoved(const std::string &bundleName, const int userId) +{ + GTEST_LOG_(INFO) << "OnBundleRemoved bundle name " << bundleName << "is exist"; + GTEST_LOG_(INFO) << "bundle name is " << bundleName << "is exist"; + BmsLauncherServiceSystemTest::Complete(BUNDLE_REMOVE); +} + +sptr TestBundleStatusCallback::AsObject() +{ + return nullptr; +} + +StatusReceiverImpl::StatusReceiverImpl() +{ + APP_LOGI("create status receiver instance"); +} + +StatusReceiverImpl::~StatusReceiverImpl() +{ + APP_LOGI("destroy status receiver instance"); +} +void StatusReceiverImpl::OnStatusNotify(const int progress) +{ + APP_LOGI("OnStatusNotify"); +} +void StatusReceiverImpl::OnFinished(const int32_t resultCode, const std::string &resultMsg) +{ + APP_LOGD("on finished result is %{public}d, %{public}s", resultCode, resultMsg.c_str()); + resultMsgSignal_.set_value(resultMsg); +} + +std::string StatusReceiverImpl::GetResultMsg() const +{ + auto future = resultMsgSignal_.get_future(); + future.wait(); + std::string resultMsg = future.get(); + if (resultMsg == MSG_SUCCESS) { + return OPERATION_SUCCESS; + } else { + return OPERATION_FAILED + resultMsg; + } +} +/** + * @tc.number: BMS_Register_0100 + * @tc.name: test launcher service RegisterCallback + * @tc.desc: register callback and listen for add events + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_Register_0100"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = "com.example.third1"; + std::string message; + std::shared_ptr launcherservice = std::make_shared(); + sptr callback = new TestBundleStatusCallback(); + launcherservice->RegisterCallback(callback); + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + EXPECT_TRUE(Wait(BUNDLE_ADD)); + launcherservice->UnRegisterCallback(); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_Register_0100"; +} +/** + * @tc.number: BMS_Register_0200 + * @tc.name: test launcher service RegisterCallback + * @tc.desc: register callback and listen for remove events + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_Register_0200"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = "com.example.third1"; + std::string message; + std::shared_ptr launcherservice = std::make_shared(); + sptr callback = new TestBundleStatusCallback(); + launcherservice->RegisterCallback(callback); + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Uninstall(bundleName, message); + EXPECT_TRUE(Wait(BUNDLE_REMOVE)); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + launcherservice->UnRegisterCallback(); + GTEST_LOG_(INFO) << "END BMS_Register_0200"; +} +/** + * @tc.number: BMS_Register_0300 + * @tc.name: test launcher service RegisterCallback + * @tc.desc: register callback and listen for update events + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_Register_0300"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; + std::string message; + std::shared_ptr launcherservice = std::make_shared(); + sptr callback = new TestBundleStatusCallback(); + launcherservice->RegisterCallback(callback); + Install(bundleFilePath1, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + EXPECT_TRUE(Wait(BUNDLE_ADD)); + Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); + EXPECT_EQ(message, "Success") << "install fail!"; + EXPECT_TRUE(Wait(BUNDLE_UPDATE)); + launcherservice->UnRegisterCallback(); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_Register_0300"; +} +/** + * @tc.number: BMS_Register_0400 + * @tc.name: test launcher service RegisterCallback + * @tc.desc: unregister callback and listen for events + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_Register_0400"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; + std::string message; + std::shared_ptr launcherservice = std::make_shared(); + sptr callback = new TestBundleStatusCallback(); + launcherservice->RegisterCallback(callback); + launcherservice->UnRegisterCallback(); + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + EXPECT_FALSE(Wait(BUNDLE_ADD)); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_Register_0400"; +} +/** + * @tc.number: BMS_GetAbilityList_0100 + * @tc.name: test GetAbilityList by LauncherService + * @tc.desc: 1.install a normal hap + * 2.get ability info of the installed hap by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetAbilityList_0100"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = "com.example.third1"; + std::string abilityName = "com.example.third1.MainAbility"; + std::string message; + int userId = Constants::DEFAULT_USERID; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + std::shared_ptr launcherservice = std::make_shared(); + std::vector launcherAbilityInfos; + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_TRUE(result) << "Get ability list failed"; + EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; + EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); + + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0100"; +} +/** + * @tc.number: BMS_GetAbilityList_0200 + * @tc.name: test GetAbilityList by LauncherService + * @tc.desc: 1.install a low version hap + * 2.install a high version hap + * 3.get the ability info of the high version hap by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetAbilityList_0200"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; + std::string abilityName = "com.example.third4.MainAbility"; + std::string message; + int userId = Constants::DEFAULT_USERID; + + Install(bundleFilePath1, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + std::shared_ptr launcherservice = std::make_shared(); + std::vector launcherAbilityInfos; + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_TRUE(result) << "Get ability list failed"; + EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; + EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); + + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0200"; +} +/** + * @tc.number: BMS_GetAbilityList_0300 + * @tc.name: test GetAbilityList by LauncherService + * @tc.desc: 1.install a normal hap with two abilty + * 2.get ability info of the installed hap by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetAbilityList_0300"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle5.hap"; + std::string bundleName = "com.example.third5"; + std::string abilityName1 = "com.example.third5A.MainAbility"; + std::string abilityName2 = "com.example.third5B.MainAbility"; + std::string message; + int userId = Constants::DEFAULT_USERID; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::vector launcherAbilityInfos; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_TRUE(result) << "Get ability list failed"; + EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; + EXPECT_EQ(launcherAbilityInfos.size(), TWO); + EXPECT_EQ(launcherAbilityInfos[0].name, abilityName1); + EXPECT_EQ(launcherAbilityInfos[1].name, abilityName2); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0300"; +} +/** + * @tc.number: BMS_GetAbilityList_0400 + * @tc.name: test GetAbilityList by LauncherService + * @tc.desc: 1.install a hap with moduletype of entry + * 2.install a hap with moduletype of feature + * 2.get ability informations of two types of haps + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetAbilityList_0400"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle3.hap"; + std::string abilityName1 = "com.example.third1.MainAbility"; + std::string abilityName2 = "com.example.third1F.MainAbility"; + std::string bundleName = "com.example.third1"; + std::string message; + + int userId = Constants::DEFAULT_USERID; + Install(bundleFilePath1, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Install(bundleFilePath2, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::vector launcherAbilityInfos; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_TRUE(result) << "Get ability list failed"; + EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; + EXPECT_EQ(launcherAbilityInfos.size(), TWO); + EXPECT_EQ(launcherAbilityInfos[0].name, abilityName1); + EXPECT_EQ(launcherAbilityInfos[1].name, abilityName2); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0400"; +} +/** + * @tc.number: BMS_GetAbilityList_0500 + * @tc.name: test GetAbilityList by LauncherService + * @tc.desc: get ability info by wrong bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0500, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "START BMS_GetAbilityList_0500"; + std::string bundleName = ""; + int userId = Constants::DEFAULT_USERID; + + std::vector launcherAbilityInfos; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0500"; +} +/** + * @tc.number: BMS_GetAbilityList_0600 + * @tc.name: test GetAbilityList by LauncherService + * @tc.desc: 1.install a normal hap + * 2.get ability info of this hap by bundleName + * 2.get ability info after uninstalling the hap + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0600, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "START BMS_GetAbilityList_0600"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = "com.example.third1"; + std::string abilityName = "com.example.third1.MainAbility"; + std::string message; + int userId = Constants::DEFAULT_USERID; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + std::shared_ptr launcherservice = std::make_shared(); + std::vector launcherAbilityInfos; + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result1 = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_TRUE(result1) << "Get ability list failed"; + EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; + EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); + + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + + bool result2 = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_FALSE(result2); + GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0600"; +} +/** + * @tc.number: BMS_GetAbilityList_0700 + * @tc.name: test GetAbilityList by LauncherService + * @tc.desc: 1.get the ability info of system app + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0700, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetAbilityList_0700"; + std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.system1.MainAbility"; + int userId = Constants::DEFAULT_USERID; + + std::vector launcherAbilityInfos; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); + EXPECT_TRUE(result); + EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; + EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); + + GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0700"; +} +/** + * @tc.number: BMS_GetAbilityInfo_0100 + * @tc.name: test GetAbilityInfo by LauncherService + * @tc.desc: 1.install a normal hap with an ability + * 2.get the ability info by want + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START GetAbilityInfo_0100"; + std::string message; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.third1.MainAbility"; + int userId = Constants::DEFAULT_USERID; + + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + Want want; + ElementName name; + name.SetAbilityName(abilityName); + name.SetBundleName(bundleName); + want.SetElement(name); + + LauncherAbilityInfo launcherAbilityInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool Result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); + EXPECT_TRUE(Result); + EXPECT_EQ(launcherAbilityInfo.name, abilityName); + + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END GetAbilityInfo_0100"; +} +/** + * @tc.number: BMS_GetAbilityInfo_0200 + * @tc.name: test GetAbilityInfo by LauncherService + * @tc.desc: 1.install a normal hap with two ability + * 2.get one ability info of the abilities by want + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0200, Function | MediumTest | Level2) +{ + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle5.hap"; + std::string bundleName = "com.example.third5"; + std::string abilityName = "com.example.third5B.MainAbility"; + std::string message; + int userId = Constants::DEFAULT_USERID; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + Want want; + ElementName name; + name.SetAbilityName(abilityName); + name.SetBundleName(bundleName); + want.SetElement(name); + + LauncherAbilityInfo launcherAbilityInfos; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfos); + EXPECT_TRUE(result) << "Get ability list failed"; + EXPECT_EQ(launcherAbilityInfos.name, abilityName); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END GetAbilityInfo_0200"; +} +/** + * @tc.number: BMS_GetAbilityInfo_0300 + * @tc.name: test GetAbilityInfo by LauncherService + * @tc.desc: 1.install a normal hap with an ability + * 2.get ability info after uninstalling the hap + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0300, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "START GetAbilityInfo_0300"; + std::string message; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.third1.MainAbility"; + int userId = Constants::DEFAULT_USERID; + + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + + Want want; + ElementName name; + name.SetAbilityName(abilityName); + name.SetBundleName(bundleName); + want.SetElement(name); + LauncherAbilityInfo launcherAbilityInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "END GetAbilityInfo_0300"; +} +/** + * @tc.number: BMS_GetAbilityInfo_0400 + * @tc.name: test GetAbilityInfo by LauncherService + * @tc.desc: 1.get the ability info of system app by want + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START GetAbilityInfo_0400"; + std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.system1.MainAbility"; + int userId = Constants::DEFAULT_USERID; + Want want; + ElementName name; + name.SetAbilityName(abilityName); + name.SetBundleName(bundleName); + want.SetElement(name); + + LauncherAbilityInfo launcherAbilityInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool Result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); + EXPECT_TRUE(Result); + EXPECT_EQ(launcherAbilityInfo.name, abilityName); + + GTEST_LOG_(INFO) << "END GetAbilityInfo_0400"; +} +/** + * @tc.number: BMS_GetAbilityInfo_0500 + * @tc.name: test GetAbilityInfo by LauncherService + * @tc.desc: 1.install a low version hap + * 2.install a high version hap + * 3.get the ability info of the high version hap by want + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START GetAbilityInfo_0500"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; + std::string abilityName = "com.example.third4.MainAbility"; + std::string message; + int userId = Constants::DEFAULT_USERID; + + Install(bundleFilePath1, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + Want want; + ElementName name; + name.SetAbilityName(abilityName); + name.SetBundleName(bundleName); + want.SetElement(name); + + LauncherAbilityInfo launcherAbilityInfos; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfos); + EXPECT_TRUE(result); + EXPECT_EQ(launcherAbilityInfos.name, abilityName); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END GetAbilityInfo_0500"; +} +/** + * @tc.number: BMS_GetApplicationInfo_0100 + * @tc.name: test GetApplicationInfo by LauncherService + * @tc.desc: get the application info of third app by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetApplicationInfo_0100"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = "com.example.third1"; + std::string message; + int userId = Constants::DEFAULT_USERID; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + ApplicationInfo appInfo; + ApplicationFlag flag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; + bool result = launcherservice->GetApplicationInfo(bundleName, flag, userId, appInfo); + EXPECT_TRUE(result); + EXPECT_EQ(appInfo.name, bundleName); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0100"; +} +/** + * @tc.number: BMS_GetApplicationInfo_0200 + * @tc.name: test GetApplicationInfo by LauncherService + * @tc.desc: get the application info with perms of third app by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START GetApplicationInfo_0200"; + std::string message; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "6"; + int userId = Constants::DEFAULT_USERID; + + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + ApplicationInfo applicationInfo; + bool Result = launcherservice->GetApplicationInfo( + bundleName, ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, userId, applicationInfo); + EXPECT_TRUE(Result); + + CommonTool commonTool; + std::string permissions = commonTool.VectorToStr(applicationInfo.permissions); + EXPECT_EQ(permissions, CAMERA); + EXPECT_EQ(applicationInfo.name, bundleName); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END GetApplicationInfo_0200"; +} +/** + * @tc.number: BMS_GetApplicationInfo_0300 + * @tc.name: test GetApplicationInfo by LauncherService + * @tc.desc: get the application info of system app by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START GetApplicationInfo_0300"; + std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; + int userId = Constants::DEFAULT_USERID; + + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + ApplicationInfo applicationInfo; + bool Result = launcherservice->GetApplicationInfo( + bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, applicationInfo); + EXPECT_TRUE(Result); + EXPECT_EQ(applicationInfo.name, bundleName); + GTEST_LOG_(INFO) << "END GetApplicationInfo_0300"; +} +/** + * @tc.number: BMS_GetApplicationInfo_0400 + * @tc.name: test GetAbilityInfo by LauncherService + * @tc.desc: 1.install a low version hap + * 2.install a high version hap + * 3.get the application info of the high version hap by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetApplicationInfo_0400"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; + std::string message; + int userId = Constants::DEFAULT_USERID; + + Install(bundleFilePath1, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + ApplicationInfo applicationInfo; + bool Result = launcherservice->GetApplicationInfo( + bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, applicationInfo); + EXPECT_TRUE(Result); + EXPECT_EQ(applicationInfo.name, bundleName); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0400"; +} +/** + * @tc.number: BMS_GetApplicationInfo_0500 + * @tc.name: test GetApplicationInfo by LauncherService + * @tc.desc: get the application info after uninstalling the hap + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0500, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "START BMS_GetApplicationInfo_0500"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = "com.example.third1"; + std::string message; + int userId = Constants::DEFAULT_USERID; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + ApplicationInfo appInfo; + bool result = + launcherservice->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0500"; +} +/** + * @tc.number: BMS_GetApplicationInfo_0600 + * @tc.name: test GetApplicationInfo by LauncherService + * @tc.desc: get the application info by invalid bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0600, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "START BMS_GetApplicationInfo_0600"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = ""; + int userId = Constants::DEFAULT_USERID; + + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + ApplicationInfo appInfo; + bool result = + launcherservice->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0600"; +} +/** + * @tc.number: BMS_IsAbilityEnabled_0100 + * @tc.name: test IsAbilityEnabled by LauncherService + * @tc.desc: check weather the ability of third hap can be enabled by abilityinfo + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_IsAbilityEnabled_0100"; + std::string message; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.third1.MainAbility"; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + AbilityInfo abilityInfo; + abilityInfo.bundleName = bundleName; + abilityInfo.name = abilityName; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); + EXPECT_TRUE(result); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0100"; +} +/** + * @tc.number: BMS_IsAbilityEnabled_0200 + * @tc.name: test IsAbilityEnabled by LauncherService + * @tc.desc: check weather the ability of system hap can be enabled by abilityinfo + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_IsAbilityEnabled_0200"; + std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.system1.MainAbility"; + AbilityInfo abilityInfo; + abilityInfo.bundleName = bundleName; + abilityInfo.name = abilityName; + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + APP_LOGE("bundle mgr proxy is nullptr."); + EXPECT_EQ(bundleMgrProxy, nullptr); + } + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0200"; +} +/** + * @tc.number: BMS_IsAbilityEnabled_0300 + * @tc.name: test IsAbilityEnabled by LauncherService + * @tc.desc: check weather the ability of hap can be enabled by invalid abilityName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0300, Function | MediumTest | Level2) +{ + GTEST_LOG_(INFO) << "START BMS_IsAbilityEnabled_0300"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.wrong.MainAbility"; + AbilityInfo abilityInfo; + abilityInfo.bundleName = bundleName; + abilityInfo.name = abilityName; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0300"; +} +/** + * @tc.number: BMS_IsAbilityEnabled_0400 + * @tc.name: test IsAbilityEnabled by LauncherService + * @tc.desc: 1.set ability enabled true + * 2.check weather the ability enabled is true by abilityinfo + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_IsAbilityEnabled_0400"; + std::string message; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string abilityName = "com.example.third1.MainAbility"; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + AbilityInfo abilityInfo; + abilityInfo.bundleName = bundleName; + abilityInfo.name = abilityName; + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!bundleMgrProxy) { + APP_LOGE("bundle mgr proxy is nullptr."); + EXPECT_EQ(bundleMgrProxy, nullptr); + } + bool ret = bundleMgrProxy->SetAbilityEnabled(abilityInfo, true); + EXPECT_TRUE(ret); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); + EXPECT_TRUE(result); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0400"; +} +/** + * @tc.number: BMS_IsBundleEnabled_0100 + * @tc.name: test IsBundleEnabled by LauncherService + * @tc.desc: check weather the application of third hap can be enabled by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0100"; + std::string message; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsBundleEnabled(bundleName); + EXPECT_TRUE(result); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0100"; +} +/** + * @tc.number: BMS_IsBundleEnabled_0100 + * @tc.name: test IsBundleEnabled by LauncherService + * @tc.desc: 1.set application enabled false + * 2.check the application enabled is false by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0200"; + std::string message; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::shared_ptr launcherservice = std::make_shared(); + sptr bundleMgrProxy = GetBundleMgrProxy(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool ret = bundleMgrProxy->SetApplicationEnabled(bundleName, false); + EXPECT_TRUE(ret); + bool result = launcherservice->IsBundleEnabled(bundleName); + EXPECT_FALSE(result); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0200"; +} +/** + * @tc.number: BMS_IsBundleEnabled_0300 + * @tc.name: test IsBundleEnabled by LauncherService + * @tc.desc: check weather the application of system hap can be enabled by bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0300"; + std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsBundleEnabled(bundleName); + EXPECT_TRUE(result); + GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0300"; +} +/** + * @tc.number: BMS_IsBundleEnabled_0400 + * @tc.name: test IsBundleEnabled by LauncherService + * @tc.desc: check weather the application of hap can be enabled by invalid bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0400"; + std::string bundleName = ""; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsBundleEnabled(bundleName); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0400"; +} +/** + * @tc.number: BMS_GetShortcutInfos_0100 + * @tc.name: test GetShortcutInfos by LauncherService + * @tc.desc: get the shortcut information of a normal hap + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetShortcutInfos_0100"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleName = "com.example.third1"; + std::string shortcutId = "id.third1"; + std::string message; + + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::vector launcherShortcutInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + EXPECT_TRUE(result) << "Get shortcut info failed"; + EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut infos is empty"; + EXPECT_EQ(launcherShortcutInfo[0].bundleName, bundleName); + EXPECT_EQ(launcherShortcutInfo[0].shortcutid, shortcutId); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetShortcutInfos_0100"; +} +/** + * @tc.number: BMS_GetShortcutInfos_0200 + * @tc.name: test GetShortcutInfos by LauncherService + * @tc.desc: 1.install a hap with moduletype of entry + * 2.install a hap with moduletype of feature + * 3.get the shortcut information of two types of haps + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetShortcutInfos_0200"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle3.hap"; + std::string bundleName = "com.example.third1"; + std::string shortcutId1 = "id.third1"; + std::string shortcutId2 = "id.third3"; + std::string message; + + Install(bundleFilePath1, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Install(bundleFilePath2, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::vector launcherShortcutInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + EXPECT_TRUE(result) << "Get shortcut info failed"; + EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut infos is empty"; + EXPECT_EQ(launcherShortcutInfo.size(), TWO); + EXPECT_EQ(launcherShortcutInfo[0].shortcutid, shortcutId1); + EXPECT_EQ(launcherShortcutInfo[1].shortcutid, shortcutId2); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetShortcutInfos_0200"; +} +/** + * @tc.number: BMS_GetShortcutInfos_0300 + * @tc.name: test GetShortcutInfos by LauncherService + * @tc.desc: get the shortcut information of a hap without shortcut in config.json + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetShortcutInfos_0300"; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; + std::string bundleName = "com.example.third2"; + std::string message; + + Install(bundleFilePath, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + std::vector launcherShortcutInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + EXPECT_FALSE(result); + EXPECT_TRUE(launcherShortcutInfo.empty()); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetShortcutInfos_0300"; +} +/** + * @tc.number: BMS_GetShortcutInfos_0400 + * @tc.name: test GetShortcutInfos by LauncherService + * @tc.desc: get the shortcut information of a hap by invalid bundleName + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetShortcutInfos_0400"; + std::string bundleName = ""; + std::vector launcherShortcutInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "END BMS_GetShortcutInfos_0400"; +} +/** + * @tc.number: BMS_GetShortcutInfos_0500 + * @tc.name: test GetShortcutInfos by LauncherService + * @tc.desc: 1.install a low version hap + * 2.install a high version hap + * 3.get the shortcut info of the high version hap by want + */ +HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "START BMS_GetShortcutInfos_0500"; + std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; + std::string shortcutId = "id.third4"; + std::string message; + + Install(bundleFilePath1, InstallFlag::NORMAL, message); + EXPECT_EQ(message, "Success") << "install fail!"; + Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); + EXPECT_EQ(message, "Success") << "install fail!"; + + std::vector launcherShortcutInfo; + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); + EXPECT_TRUE(result); + EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut info is empty"; + EXPECT_EQ(launcherShortcutInfo[0].bundleName, bundleName); + EXPECT_EQ(launcherShortcutInfo[0].shortcutid, shortcutId); + Uninstall(bundleName, message); + EXPECT_EQ(message, "Success") << "uninstall fail!"; + GTEST_LOG_(INFO) << "END BMS_GetShortcutInfos_0500"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp b/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp index b13b31d33b4047834c02af2163b0cf5e944ffc34..3ed774b21716b8412dfd1f73cf86bcd2ccd00fc9 100644 --- a/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp +++ b/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp @@ -14,6 +14,7 @@ */ #include +#include #include #include @@ -51,6 +52,9 @@ public: virtual ~BundleStatusCallbackImpl() override; virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) override; + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override{}; + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override{}; + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override{}; private: DISALLOW_COPY_AND_MOVE(BundleStatusCallbackImpl); @@ -170,7 +174,6 @@ public: static sptr GetBundleMgrProxy(); static sptr GetInstallerProxy(); bool QueryJsonFile(const std::string &bundleName) const; - bool CreateFile(const std::string &path) const; }; void BmsSearchSystemTest::SetUpTestCase() @@ -183,10 +186,10 @@ void BmsSearchSystemTest::SetUpTestCase() sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install bmsThirdBundle1.hap fail!"; + EXPECT_EQ(installResult, "Success") << "install bmsThirdBundle1.hap fail!"; } void BmsSearchSystemTest::TearDownTestCase() @@ -256,40 +259,6 @@ bool BmsSearchSystemTest::QueryJsonFile(const std::string &bundleName) const return true; } -bool BmsSearchSystemTest::CreateFile(const std::string &path) const -{ - if (path.size() > PATH_MAX) { - APP_LOGE("CreateFile the length of path is too long"); - return false; - } - - std::string realPath; - realPath.reserve(PATH_MAX); - realPath.resize(PATH_MAX - 1); - - if (realpath(path.c_str(), &(realPath[0])) != nullptr) { - APP_LOGW("CreateFile-translate:%{public}s already exist path", realPath.c_str()); - return true; - } - - mode_t mode = 0666; - int fd = open(realPath.c_str(), O_RDWR | O_CREAT, mode); - if (fd == -1) { - APP_LOGE("CreateFile-open:%{public}s error", realPath.c_str()); - return false; - } - if (close(fd) != 0) { - APP_LOGW("CreateFile-close:%{public}s error", realPath.c_str()); - return false; - } - - if (access(realPath.c_str(), F_OK) != 0) { - APP_LOGE("CreateFile-checkFile:%{public}s not exist", realPath.c_str()); - return false; - } - return true; -} - void BmsSearchSystemTest::Install( const std::string &bundleFilePath, const InstallFlag installFlag, std::vector &resvec) { @@ -303,7 +272,7 @@ void BmsSearchSystemTest::Install( installParam.installFlag = installFlag; installParam.userId = Constants::DEFAULT_USERID; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -324,7 +293,7 @@ void BmsSearchSystemTest::Uninstall(const std::string &bundleName, std::vector statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -345,7 +314,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0100, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; @@ -379,7 +348,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0200, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; @@ -412,7 +381,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0300, Function | MediumTest | Level2) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } appName = BASE_BUNDLE_NAME + "e"; @@ -437,7 +406,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0400, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; @@ -465,7 +434,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0500, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; @@ -494,7 +463,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0600, Function | MediumTest | Level2) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; @@ -524,7 +493,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0700, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleArchiveInfo(hapFilePath, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_TRUE(getInfoResult); @@ -548,7 +517,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0800, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoResult = bundleMgrProxy->GetBundleArchiveInfo(hapFilePath, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo); @@ -583,7 +552,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_0900, Function | MediumTest | Level2) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } hapFilePath = THIRD_BUNDLE_PATH + "tt.hap"; bool getInfoResult = bundleMgrProxy->GetBundleArchiveInfo(hapFilePath, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -607,7 +576,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1000, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int userId = Constants::DEFAULT_USERID; @@ -632,7 +601,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1100, Function | MediumTest | Level2) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int userId = Constants::DEFAULT_USERID; @@ -658,7 +627,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1200, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; @@ -689,14 +658,14 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1300, Function | MediumTest | Level1) Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success"); + EXPECT_EQ(installResult, "Success"); resvec.clear(); bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle8.hap"; Install(bundleFilePath, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success"); + EXPECT_EQ(installResult, "Success"); std::string bundleName = BASE_BUNDLE_NAME + "3"; std::string appPermission = "com.example.permission"; @@ -704,7 +673,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1300, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int result = bundleMgrProxy->CheckPermission(bundleName, appPermission); EXPECT_EQ(result, 0); @@ -712,12 +681,12 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1300, Function | MediumTest | Level1) std::vector resvec2; Uninstall(bundleName, resvec2); std::string uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success"); + EXPECT_EQ(uninstallResult, "Success"); resvec2.clear(); bundleName = BASE_BUNDLE_NAME + "2"; Uninstall(bundleName, resvec2); uninstallResult = commonTool.VectorToStr(resvec2); - ASSERT_EQ(uninstallResult, "Success"); + EXPECT_EQ(uninstallResult, "Success"); std::cout << "END BMS_SEARCH_1300" << std::endl; } @@ -737,7 +706,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1400, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int result = bundleMgrProxy->CheckPermission(bundleName, appPermission); @@ -760,7 +729,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1500, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string installResult; for (int i = 7; i < 9; i++) { @@ -768,7 +737,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1500, Function | MediumTest | Level1) std::string hapFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle" + std::to_string(i) + ".hap"; Install(hapFilePath, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; } std::vector bundleInfos; @@ -802,7 +771,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1600, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector bundleInfos; bool getInfoResult = bundleMgrProxy->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos); @@ -824,7 +793,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1700, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string installResult; int userId = Constants::DEFAULT_USERID; @@ -834,7 +803,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1700, Function | MediumTest | Level1) std::string appName = BASE_BUNDLE_NAME + std::to_string(i - 5); bool queryResult = QueryJsonFile(appName); - ASSERT_TRUE(queryResult); + EXPECT_TRUE(queryResult); std::vector appInfos; bool getInfoResult = @@ -865,7 +834,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1800, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector appInfos; bool getInfoResult = @@ -888,7 +857,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_1900, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int userId = Constants::DEFAULT_USERID; @@ -912,7 +881,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_2000, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool queryResult = QueryJsonFile(bundleName); @@ -942,14 +911,14 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_2100, Function | MediumTest | Level1) std::string firstBundleName = BASE_BUNDLE_NAME + "2"; bool queryResult = QueryJsonFile(firstBundleName); - ASSERT_TRUE(queryResult); + EXPECT_TRUE(queryResult); resvec.clear(); std::string hapFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle8.hap"; std::string secondBundleName = BASE_BUNDLE_NAME + "3"; queryResult = QueryJsonFile(secondBundleName); - ASSERT_TRUE(queryResult); + EXPECT_TRUE(queryResult); bundleMgrProxy->CheckPublicKeys(firstBundleName, secondBundleName); for (int32_t i = 2; i <= 3; i++) { @@ -979,7 +948,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_2200, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } Want want; ElementName name; @@ -1101,7 +1070,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_2800, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleMgrProxy = GetBundleMgrProxy(); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; bool queryResult = QueryJsonFile(appName); EXPECT_TRUE(queryResult); @@ -1221,7 +1190,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3300, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } BundleInfo bundleInfo; @@ -1233,7 +1202,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3300, Function | MediumTest | Level1) EXPECT_EQ(commonTool.VectorToStr(bundleInfo.modulePublicDirs), "/data/accounts/account_0/appdata/com.third.hiworld.example1/com.third.hiworld.example.h1"); EXPECT_EQ(commonTool.VectorToStr(bundleInfo.hapModuleNames), "com.third.hiworld.example.h1"); - EXPECT_EQ(commonTool.VectorToStr(bundleInfo.moduleNames), "bmsThirdBundle1"); + EXPECT_EQ(commonTool.VectorToStr(bundleInfo.moduleNames), "testability"); std::cout << "END BMS_Search_3300" << std::endl; } @@ -1253,7 +1222,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3400, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } ApplicationInfo appInfo; @@ -1291,7 +1260,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3500, Function | MediumTest | Level1) bool queryResult = bundleMgrProxy->GetHapModuleInfo(abilityInfo, hapModuleInfo); EXPECT_EQ(hapModuleInfo.name, "com.third.hiworld.example.h1"); - EXPECT_EQ(hapModuleInfo.moduleName, "bmsThirdBundle1"); + EXPECT_EQ(hapModuleInfo.moduleName, "testability"); EXPECT_TRUE(queryResult); std::cout << "END BMS_SEARCH_3500" << std::endl; } @@ -1311,7 +1280,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3600, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector resvec; std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; @@ -1319,14 +1288,14 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3600, Function | MediumTest | Level1) CommonTool commonTool; sptr bundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(bundleStatusCallback, nullptr); + EXPECT_NE(bundleStatusCallback, nullptr); bundleStatusCallback->SetBundleName(appName); bundleMgrProxy->RegisterBundleStatusCallback(bundleStatusCallback); Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; bool queryResult = QueryJsonFile(appName); - ASSERT_TRUE(queryResult); + EXPECT_TRUE(queryResult); Uninstall(appName, resvec); std::cout << "END BMS_SEARCH_3600" << std::endl; bundleMgrProxy->UnregisterBundleStatusCallback(); @@ -1347,7 +1316,7 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3700, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::vector resvec; std::string firstFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle8.hap"; @@ -1357,21 +1326,21 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3700, Function | MediumTest | Level1) CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(firstBundleStatusCallback, nullptr); + EXPECT_NE(firstBundleStatusCallback, nullptr); firstBundleStatusCallback->SetBundleName(firstAppName); bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string firstinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(firstinstallResult, "Success") << "install fail!"; + EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); - ASSERT_NE(secondBundleStatusCallback, nullptr); + EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); std::string secondinstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(secondinstallResult, "Success") << "install fail!"; + EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; bundleMgrProxy->ClearBundleStatusCallback(firstBundleStatusCallback); for (int32_t i = 2; i <= 3; i++) { @@ -1397,24 +1366,28 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3800, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appName = BASE_BUNDLE_NAME + "1"; - const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/name1.txt"; - const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/cache/name2.txt"; - bool isSuccess = CreateFile(testCacheFileNamE1); - ASSERT_TRUE(isSuccess); - isSuccess = CreateFile(testCacheFileNamE2); - ASSERT_TRUE(isSuccess); + const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/name1.txt"; + const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + appName + "/cache/name2.txt"; + std::ofstream file1(testCacheFileNamE1); + std::ofstream file2(testCacheFileNamE2); + file1.close(); + file2.close(); + int name1Exist = access(testCacheFileNamE1.c_str(), F_OK); + EXPECT_EQ(name1Exist, 0); + int name2Exist = access(testCacheFileNamE2.c_str(), F_OK); + EXPECT_EQ(name2Exist, 0); sptr bundleCleanCacheCallback = (new (std::nothrow) CleanCacheCallBackImpl()); - ASSERT_NE(bundleCleanCacheCallback, nullptr); + EXPECT_NE(bundleCleanCacheCallback, nullptr); bundleMgrProxy->CleanBundleCacheFiles(appName, bundleCleanCacheCallback); EXPECT_TRUE(bundleCleanCacheCallback->GetSucceededResult()); - int name1Exist = access(testCacheFileNamE1.c_str(), F_OK); + name1Exist = access(testCacheFileNamE1.c_str(), F_OK); EXPECT_NE(name1Exist, 0) << "the cache test file1 exists."; - int name2Exist = access(testCacheFileNamE2.c_str(), F_OK); + name2Exist = access(testCacheFileNamE2.c_str(), F_OK); EXPECT_NE(name2Exist, 0) << "the cache test file2 exists."; std::cout << "END BMS_SEARCH_3800" << std::endl; } @@ -1432,22 +1405,26 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3900, Function | MediumTest | Level1) sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } std::string appName = BASE_BUNDLE_NAME + "1"; - const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/files/name1.txt"; - const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + "/" + appName + "/files/name2.txt"; - bool isSuccess = CreateFile(testCacheFileNamE1); - ASSERT_TRUE(isSuccess); - isSuccess = CreateFile(testCacheFileNamE2); - ASSERT_TRUE(isSuccess); - bundleMgrProxy->CleanBundleDataFiles(appName); + const std::string testCacheFileNamE1 = BUNDLE_DATA_ROOT_PATH + appName + "/files/name1.txt"; + const std::string testCacheFileNamE2 = BUNDLE_DATA_ROOT_PATH + appName + "/files/name2.txt"; + std::ofstream file1(testCacheFileNamE1); + std::ofstream file2(testCacheFileNamE2); + file1.close(); + file2.close(); int name1Exist = access(testCacheFileNamE1.c_str(), F_OK); - ASSERT_NE(name1Exist, 0) << "the test file1 exists."; + EXPECT_EQ(name1Exist, 0) << "the test file1 exists."; int name2Exist = access(testCacheFileNamE2.c_str(), F_OK); - ASSERT_NE(name2Exist, 0) << "the test file2 exists."; + EXPECT_EQ(name2Exist, 0) << "the test file2 exists."; + bundleMgrProxy->CleanBundleDataFiles(appName); + name1Exist = access(testCacheFileNamE1.c_str(), F_OK); + EXPECT_NE(name1Exist, 0) << "the test file1 exists."; + name2Exist = access(testCacheFileNamE2.c_str(), F_OK); + EXPECT_NE(name2Exist, 0) << "the test file2 exists."; std::cout << "END BMS_SEARCH_3900" << std::endl; } diff --git a/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp b/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp index cff680036637c47f025d14f887c0d887f44d8d1e..aff2267f599c8beb95e1dfe7c1939405a717bbc3 100755 --- a/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp +++ b/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp @@ -188,11 +188,11 @@ void BmsUninstallSystemTest::CheckBundleInfo(const std::string &version, const s sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoRresult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); - ASSERT_TRUE(getInfoRresult); + EXPECT_TRUE(getInfoRresult); EXPECT_EQ(bundleInfo.name, bundleName); EXPECT_EQ(bundleInfo.versionName, version); } @@ -282,7 +282,7 @@ void BmsUninstallSystemTest::Install( installParam.installFlag = installFlag; installParam.userId = Constants::DEFAULT_USERID; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -303,7 +303,7 @@ void BmsUninstallSystemTest::Uninstall(const std::string &bundleName, std::vecto InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -326,7 +326,7 @@ void BmsUninstallSystemTest::HapUninstall( InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, modulePackage, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -348,7 +348,7 @@ void BmsUninstallSystemTest::UninstallWithoutResvec(const std::string &bundleNam } else { InstallParam installParam; sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); - ASSERT_NE(statusReceiver, nullptr); + EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); } @@ -371,11 +371,11 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0100, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); - ASSERT_TRUE(isInstallSucceed); + EXPECT_TRUE(isInstallSucceed); std::string version = "1.0"; CheckBundleInfo(version, bundleName); @@ -383,7 +383,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0100, Function | MediumTest | Lev resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -409,7 +409,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0200, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -425,7 +425,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0200, Function | MediumTest | Lev resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -448,7 +448,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0300, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -464,7 +464,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0300, Function | MediumTest | Lev bundleName = BASE_BUNDLE_NAME + "1"; Uninstall(bundleName, resvec); uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; std::cout << "BMS_Uninstall_0300 end" << std::endl; } @@ -489,7 +489,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0400, Function | MediumTest | Lev Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -498,7 +498,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0400, Function | MediumTest | Lev resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -523,7 +523,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0500, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -557,7 +557,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0600, Function | MediumTest | Lev Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; } std::vector> futureVec; @@ -581,7 +581,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0600, Function | MediumTest | Lev sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoRresult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoRresult); @@ -665,7 +665,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0900, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; std::string modulePackage = BASE_MODULE_PACKAGE + ".h1"; @@ -675,7 +675,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_0900, Function | MediumTest | Lev resvec.clear(); HapUninstall(bundleName, modulePackage, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -706,18 +706,18 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1000, Function | MediumTest | Lev sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; Install(bundleFilePath, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; bool checkResult = CheckAppDirExist(bundleName, modulePackage1); EXPECT_TRUE(checkResult); @@ -727,7 +727,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1000, Function | MediumTest | Lev resvec.clear(); HapUninstall(bundleName, modulePackage2, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; checkResult = CheckAppDirExist(bundleName, modulePackage1); EXPECT_TRUE(checkResult); @@ -765,7 +765,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1100, Function | MediumTest | Lev CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "5"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -774,7 +774,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1100, Function | MediumTest | Lev resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -797,12 +797,12 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1200, Function | MediumTest | Lev sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } Install(bundleFilePath, InstallFlag::NORMAL, resvec); CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "5"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); EXPECT_TRUE(isInstallSucceed); @@ -812,7 +812,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1200, Function | MediumTest | Lev bool result = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(result); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); std::cout << "BMS_Uninstall_1200 end" << std::endl; @@ -840,18 +840,18 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1300, Function | MediumTest | Lev sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; Install(bundleFilePath, InstallFlag::NORMAL, resvec); installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; bool checkResult = CheckAppDirExist(bundleName, modulePackage1); EXPECT_TRUE(checkResult); @@ -861,7 +861,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_Uninstall_1300, Function | MediumTest | Lev resvec.clear(); HapUninstall(bundleName, modulePackage1, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; checkResult = CheckAppDirExist(bundleName, modulePackage2); EXPECT_TRUE(checkResult); @@ -900,7 +900,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0100, Function | MediumT CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -909,7 +909,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0100, Function | MediumT resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -918,7 +918,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0100, Function | MediumT sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool result = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(result); @@ -942,7 +942,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0200, Function | MediumT CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -951,7 +951,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0200, Function | MediumT resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -961,7 +961,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0200, Function | MediumT sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool result = bundleMgrProxy->CheckPermission(bundleName, permission); EXPECT_TRUE(result); @@ -985,7 +985,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0300, Function | MediumT CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -996,7 +996,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0300, Function | MediumT resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -1005,7 +1005,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0300, Function | MediumT sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int result = bundleMgrProxy->GetUidByBundleName(bundleName, userId); EXPECT_EQ(result, -1); @@ -1029,7 +1029,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0400, Function | MediumT CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -1038,7 +1038,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0400, Function | MediumT sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool infoResult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_TRUE(infoResult); @@ -1054,7 +1054,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_BundleInfoDeletion_0400, Function | MediumT resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -1088,7 +1088,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DirDeletion_0100, Function | MediumTest | L CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -1103,7 +1103,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DirDeletion_0100, Function | MediumTest | L resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -1130,7 +1130,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DirDeletion_0200, Function | MediumTest | L CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -1139,7 +1139,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DirDeletion_0200, Function | MediumTest | L resvec.clear(); Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_TRUE(isUninstallSucceed); @@ -1166,7 +1166,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DirDeletion_0300, Function | MediumTest | L CommonTool commonTool; std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + "1"; bool isInstallSucceed = CheckInstallIsSuccess(bundleName); @@ -1190,7 +1190,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DirDeletion_0300, Function | MediumTest | L resvec.clear(); Uninstall(bundleName, resvec); uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; std::cout << "BMS_DirDeletion_0300 end" << std::endl; } @@ -1212,7 +1212,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_UidTest_0100, Function | MediumTest | Level Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(installResult, "Success") << "install fail!"; + EXPECT_EQ(installResult, "Success") << "install fail!"; std::string bundleName = BASE_BUNDLE_NAME + std::to_string(i - 5); bool isInstallSucceed = CheckInstallIsSuccess(bundleName); EXPECT_TRUE(isInstallSucceed); @@ -1221,7 +1221,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_UidTest_0100, Function | MediumTest | Level sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int uid = bundleMgrProxy->GetUidByBundleName(bundleName, userId); EXPECT_GE(uid, Constants::BASE_APP_UID); @@ -1245,7 +1245,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_UidTest_0100, Function | MediumTest | Level sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } bool getInfoRresult = bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); EXPECT_FALSE(getInfoRresult); @@ -1273,7 +1273,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_UidTest_0200, Function | MediumTest | Level sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int uid = bundleMgrProxy->GetUidByBundleName(bundleName, userId); EXPECT_GE(uid, Constants::BASE_SYS_VEN_UID); @@ -1306,7 +1306,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_UidTest_0300, Function | MediumTest | Level sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); - ASSERT_EQ(bundleMgrProxy, nullptr); + EXPECT_EQ(bundleMgrProxy, nullptr); } int uid = bundleMgrProxy->GetUidByBundleName(bundleName, userId); EXPECT_GE(uid, Constants::BASE_SYS_UID); @@ -1314,7 +1314,7 @@ HWTEST_F(BmsUninstallSystemTest, BMS_UidTest_0300, Function | MediumTest | Level Uninstall(bundleName, resvec); std::string uninstallResult = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallResult, "Failure[MSG_ERR_UNINSTALL_SYSTEM_APP_ERROR]"); + EXPECT_EQ(uninstallResult, "Failure[MSG_ERR_UNINSTALL_SYSTEM_APP_ERROR]"); bool isUninstallSucceed = CheckUninstallIsSuccess(bundleName); EXPECT_FALSE(isUninstallSucceed); @@ -1343,30 +1343,30 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DFX_0500, Function | MediumTest | Level2) CommonTool commonTool; Install(bundleFilePath1, InstallFlag::NORMAL, resvec); installMsg = commonTool.VectorToStr(resvec); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath1; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath1; resvec.clear(); std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; Install(bundleFilePath2, InstallFlag::NORMAL, resvec); installMsg = commonTool.VectorToStr(resvec); - ASSERT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath2; + EXPECT_EQ(installMsg, "Success") << "install fail!" << bundleFilePath2; resvec.clear(); std::string bundleName = BASE_BUNDLE_NAME + "1"; HapUninstall(bundleName, modulePackage1, resvec); std::string uninstallMsg = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallMsg, "Success") << "unistall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "unistall fail!"; resvec.clear(); HapUninstall(bundleName, modulePackage1, resvec); uninstallMsg = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallMsg, "Failure[ERR_UNINSTALL_MISSING_INSTALLED_MODULE]"); + EXPECT_EQ(uninstallMsg, "Failure[ERR_UNINSTALL_MISSING_INSTALLED_MODULE]"); resvec.clear(); HapUninstall(bundleName, modulePackage2, resvec); uninstallMsg = commonTool.VectorToStr(resvec); - ASSERT_EQ(uninstallMsg, "Success") << "uninstall fail!"; + EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; std::cout << "END BMS_DFX_0500" << std::endl; } diff --git a/test/systemtest/common/task_dispatcher/BUILD.gn b/test/systemtest/common/task_dispatcher/BUILD.gn index c3cfdbf7e4b7a9e0fa3db628ab6000e2a727a07b..d381007b930dd0804707a3d084df9a2fa44128ff 100755 --- a/test/systemtest/common/task_dispatcher/BUILD.gn +++ b/test/systemtest/common/task_dispatcher/BUILD.gn @@ -34,7 +34,7 @@ ohos_systemtest("task_dispatcher_test") { include_dirs = [ "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/appexecfwk/standard/test/systemtest/common/task_dispatcher/include", - + "//third_party/jsoncpp/include", "//foundation/appexecfwk/standard/test/systemtest/common/ams/tool/include", "//base/notification/ces_standard/test/systemtest/common/resource", ] @@ -71,7 +71,7 @@ ohos_systemtest("task_dispatcher_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", - "//utils/native/base:utils", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/tools/bm/include/bundle_command.h b/tools/bm/include/bundle_command.h index e66f79976dca814242bbe9c221ee68b3c933fdb2..6657bec8591224e74af1d847ce16329d854c37ee 100644 --- a/tools/bm/include/bundle_command.h +++ b/tools/bm/include/bundle_command.h @@ -89,8 +89,8 @@ private: std::string DumpBundleInfo() const; std::string DumpBundleInfos() const; - int32_t InstallOperation(const std::string bundlePath, const InstallFlag installFlag) const; - int32_t UninstallOperation(const std::string bundleName, const std::string moduleName) const; + int32_t InstallOperation(const std::string &bundlePath, InstallParam &installParam) const; + int32_t UninstallOperation(const std::string &bundleName, const std::string &moduleName) const; sptr bundleMgrProxy_; sptr bundleInstallerProxy_; diff --git a/tools/bm/src/bundle_command.cpp b/tools/bm/src/bundle_command.cpp index 570559b91744ad281b4a935d6ee4be96eeee0509..913e70e6bb78c90ba40fd0e949fa6efe01be4bd9 100644 --- a/tools/bm/src/bundle_command.cpp +++ b/tools/bm/src/bundle_command.cpp @@ -30,11 +30,12 @@ namespace AppExecFwk { namespace { const std::string BUNDLE_NAME_EMPTY = ""; -const std::string SHORT_OPTIONS = "hp:rn:m:ai"; +const std::string SHORT_OPTIONS = "hp:rfn:m:ai"; const struct option LONG_OPTIONS[] = { {"help", no_argument, nullptr, 'h'}, {"bundle-path", required_argument, nullptr, 'p'}, {"replace", no_argument, nullptr, 'r'}, + {"force", no_argument, nullptr, 'f'}, {"bundle-name", required_argument, nullptr, 'n'}, {"module-name", required_argument, nullptr, 'm'}, {"all", no_argument, nullptr, 'a'}, @@ -321,7 +322,9 @@ ErrCode BundleManagerShellCommand::RunAsHelpCommand() ErrCode BundleManagerShellCommand::RunAsInstallCommand() { int result = OHOS::ERR_OK; + InstallFlag installFlag = InstallFlag::NORMAL; + bool noCheckSignature = false; int option = -1; int counter = 0; @@ -419,6 +422,12 @@ ErrCode BundleManagerShellCommand::RunAsInstallCommand() installFlag = InstallFlag::REPLACE_EXISTING; break; } + case 'f': { + // 'bm install -f' + // 'bm install -f' + noCheckSignature = true; + break; + } case 0: { break; } @@ -441,7 +450,11 @@ ErrCode BundleManagerShellCommand::RunAsInstallCommand() if (result != OHOS::ERR_OK) { resultReceiver_.append(HELP_MSG_INSTALL); } else { - int32_t installResult = InstallOperation(bundlePath, installFlag); + InstallParam installParam; + installParam.installFlag = installFlag; + installParam.noCheckSignature = noCheckSignature; + + int32_t installResult = InstallOperation(bundlePath, installParam); if (installResult == OHOS::ERR_OK) { resultReceiver_ = STRING_INSTALL_BUNDLE_OK + "\n"; } else { @@ -745,7 +758,7 @@ std::string BundleManagerShellCommand::DumpBundleInfo() const return dumpResults; } -int32_t BundleManagerShellCommand::InstallOperation(const std::string bundlePath, const InstallFlag installFlag) const +int32_t BundleManagerShellCommand::InstallOperation(const std::string &bundlePath, InstallParam &installParam) const { std::string absoluteBundlePath = ""; if (bundlePath.size() > 0) { @@ -769,17 +782,16 @@ int32_t BundleManagerShellCommand::InstallOperation(const std::string bundlePath APP_LOGI("bundlePath: %{public}s", bundlePath.c_str()); APP_LOGI("absoluteBundlePath: %{public}s", absoluteBundlePath.c_str()); - sptr statusReceiver(new StatusReceiverImpl()); - InstallParam installParam; - installParam.installFlag = installFlag; installParam.userId = 0; + sptr statusReceiver(new StatusReceiverImpl()); bundleInstallerProxy_->Install(absoluteBundlePath, installParam, statusReceiver); return statusReceiver->GetResultCode(); } -int32_t BundleManagerShellCommand::UninstallOperation(const std::string bundleName, const std::string moduleName) const +int32_t BundleManagerShellCommand::UninstallOperation( + const std::string &bundleName, const std::string &moduleName) const { sptr statusReceiver(new StatusReceiverImpl()); InstallParam installParam; diff --git a/tools/test/mock/mock_bundle_mgr_host.h b/tools/test/mock/mock_bundle_mgr_host.h index 9df3ac8d90f51a0bd1606deff5289ad622f635ed..648aeb1ef86a0d9ef9437f406b955924e0ec634d 100644 --- a/tools/test/mock/mock_bundle_mgr_host.h +++ b/tools/test/mock/mock_bundle_mgr_host.h @@ -40,6 +40,7 @@ public: MOCK_METHOD1(CheckIsSystemAppByUid, bool(const int uid)); MOCK_METHOD2(GetBundleInfosByMetaData, bool(const std::string &metaData, std::vector &bundleInfos)); MOCK_METHOD2(QueryAbilityInfo, bool(const Want &want, AbilityInfo &abilityInfo)); + MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD2(QueryAbilityInfoByUri, bool(const std::string &abilityUri, AbilityInfo &abilityInfo)); MOCK_METHOD1(QueryKeepAliveBundleInfos, bool(std::vector &bundleInfos)); MOCK_METHOD2(GetAbilityLabel, std::string(const std::string &bundleName, const std::string &className)); @@ -86,6 +87,9 @@ public: MOCK_METHOD3(GetFormsInfoByModule, bool(const std::string &bundleName, const std::string &moduleName, std::vector &formInfos)); MOCK_METHOD2(GetShortcutInfos, bool(const std::string &bundleName, std::vector &shortcutInfos)); + MOCK_METHOD2(GetModuleUsageRecords, + bool(const int32_t number, std::vector &moduleUsageRecords)); + MOCK_METHOD3(NotifyActivityLifeStatus, bool(const std::string &bundleName, const std::string &abilityName, const int64_t launchTime)); }; } // namespace AppExecFwk diff --git a/tools/test/moduletest/bm/BUILD.gn b/tools/test/moduletest/bm/BUILD.gn index 980925444e09999189a3b3852bdb987185fe8b99..6ba04f9cab234a8b9b3c327b85290ee55c3aebe8 100644 --- a/tools/test/moduletest/bm/BUILD.gn +++ b/tools/test/moduletest/bm/BUILD.gn @@ -9,7 +9,7 @@ # 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. +# limitations under the License. import("//build/test.gni") import("//foundation/appexecfwk/standard/appexecfwk.gni") @@ -58,6 +58,7 @@ ohos_moduletest("bundle_command_dump_module_test") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -65,6 +66,7 @@ ohos_moduletest("bundle_command_dump_module_test") { ] external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -96,6 +98,7 @@ ohos_moduletest("bundle_command_install_module_test") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -103,6 +106,7 @@ ohos_moduletest("bundle_command_install_module_test") { ] external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -134,6 +138,7 @@ ohos_moduletest("bundle_command_uninstall_module_test") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -141,6 +146,7 @@ ohos_moduletest("bundle_command_uninstall_module_test") { ] external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/tools/test/systemtest/bm/BUILD.gn b/tools/test/systemtest/bm/BUILD.gn old mode 100644 new mode 100755 index 858d7bb250b3693cc3908fa4edea5bfef9685682..f0157df58461f939d0a33fba7158973817e93292 --- a/tools/test/systemtest/bm/BUILD.gn +++ b/tools/test/systemtest/bm/BUILD.gn @@ -19,7 +19,10 @@ module_output_path = "appexecfwk_standard/tools" ohos_systemtest("bundle_command_install_system_test") { module_out_path = module_output_path - include_dirs = [ "${aafwk_path}/tools/test/systemtest/aa" ] + include_dirs = [ + "${aafwk_path}/tools/test/systemtest/aa", + "//third_party/jsoncpp/include", + ] sources = [ "${aafwk_path}/tools/test/systemtest/aa/tool_system_test.cpp", @@ -36,6 +39,7 @@ ohos_systemtest("bundle_command_install_system_test") { deps = [ "${aafwk_path}/tools/aa:tools_aa_source_set", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ @@ -47,7 +51,10 @@ ohos_systemtest("bundle_command_install_system_test") { ohos_systemtest("bundle_command_uninstall_system_test") { module_out_path = module_output_path - include_dirs = [ "${aafwk_path}/tools/test/systemtest/aa" ] + include_dirs = [ + "${aafwk_path}/tools/test/systemtest/aa", + "//third_party/jsoncpp/include", + ] sources = [ "${aafwk_path}/tools/test/systemtest/aa/tool_system_test.cpp", @@ -64,6 +71,7 @@ ohos_systemtest("bundle_command_uninstall_system_test") { deps = [ "${aafwk_path}/tools/aa:tools_aa_source_set", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ @@ -75,7 +83,10 @@ ohos_systemtest("bundle_command_uninstall_system_test") { ohos_systemtest("bundle_command_dump_system_test") { module_out_path = module_output_path - include_dirs = [ "${aafwk_path}/tools/test/systemtest/aa" ] + include_dirs = [ + "${aafwk_path}/tools/test/systemtest/aa", + "//third_party/jsoncpp/include", + ] sources = [ "${aafwk_path}/tools/test/systemtest/aa/tool_system_test.cpp", @@ -92,6 +103,7 @@ ohos_systemtest("bundle_command_dump_system_test") { deps = [ "${aafwk_path}/tools/aa:tools_aa_source_set", "//third_party/googletest:gtest_main", + "//third_party/jsoncpp:jsoncpp", ] external_deps = [ diff --git a/tools/test/systemtest/bm/bundle_command_install_system_test.cpp b/tools/test/systemtest/bm/bundle_command_install_system_test.cpp index 8b256dde93bade12c967478bc5c8850ee32e74aa..8bafccc461b2930003222dc2d1a6976bf20d7c28 100644 --- a/tools/test/systemtest/bm/bundle_command_install_system_test.cpp +++ b/tools/test/systemtest/bm/bundle_command_install_system_test.cpp @@ -28,6 +28,8 @@ namespace { const std::string STRING_BUNDLE_PATH = "/data/test/resource/bm/pageAbilityBundleForInstall.hap"; const std::string STRING_BUNDLE_PATH_INVALID = STRING_BUNDLE_PATH + ".invalid"; const std::string STRING_BUNDLE_NAME = "com.ohos.tools.pageAbilityBundleForInstall"; + +const std::string STRING_BUNDLE_PATH_NO_SIGNATURE = "/data/test/resource/bm/pageAbilityBundleForInstallNoSignature.hap"; } // namespace class BmCommandInstallSystemTest : public ::testing::Test { @@ -106,3 +108,43 @@ HWTEST_F(BmCommandInstallSystemTest, Bm_Command_Install_SystemTest_0300, Functio // uninstall the bundle ToolSystemTest::UninstallBundle(STRING_BUNDLE_NAME); } + +/** + * @tc.number: Bm_Command_Install_SystemTest_0400 + * @tc.name: ExecCommand + * @tc.desc: Verify the "bm install -p " command. + */ +HWTEST_F(BmCommandInstallSystemTest, Bm_Command_Install_SystemTest_0400, Function | MediumTest | Level1) +{ + // uninstall the bundle + ToolSystemTest::UninstallBundle(STRING_BUNDLE_NAME); + + // install a valid bundle with no signature + std::string command = "bm install -p " + STRING_BUNDLE_PATH_NO_SIGNATURE; + std::string commandResult = ToolSystemTest::ExecuteCommand(command); + + EXPECT_NE(commandResult, STRING_INSTALL_BUNDLE_OK + "\n"); + + // uninstall the bundle + ToolSystemTest::UninstallBundle(STRING_BUNDLE_NAME); +} + +/** + * @tc.number: Bm_Command_Install_SystemTest_0500 + * @tc.name: ExecCommand + * @tc.desc: Verify the "bm install -p -f" command. + */ +HWTEST_F(BmCommandInstallSystemTest, Bm_Command_Install_SystemTest_0500, Function | MediumTest | Level1) +{ + // uninstall the bundle + ToolSystemTest::UninstallBundle(STRING_BUNDLE_NAME); + + // install a valid bundle with no signature + std::string command = "bm install -p " + STRING_BUNDLE_PATH_NO_SIGNATURE + " -f"; + std::string commandResult = ToolSystemTest::ExecuteCommand(command); + + EXPECT_EQ(commandResult, STRING_INSTALL_BUNDLE_OK + "\n"); + + // uninstall the bundle + ToolSystemTest::UninstallBundle(STRING_BUNDLE_NAME); +} diff --git a/tools/test/unittest/bm/BUILD.gn b/tools/test/unittest/bm/BUILD.gn index 871dd3ba9530c1f9fcdd7648f72373d23a76a1d8..3f010a2d4313c1f7941556ef776f45106fc2f967 100644 --- a/tools/test/unittest/bm/BUILD.gn +++ b/tools/test/unittest/bm/BUILD.gn @@ -60,6 +60,7 @@ ohos_unittest("bundle_command_dump_test") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -67,6 +68,7 @@ ohos_unittest("bundle_command_dump_test") { ] external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -102,6 +104,7 @@ ohos_unittest("bundle_command_install_test") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -109,6 +112,7 @@ ohos_unittest("bundle_command_install_test") { ] external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -144,6 +148,7 @@ ohos_unittest("bundle_command_test") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -151,6 +156,7 @@ ohos_unittest("bundle_command_test") { ] external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] @@ -186,6 +192,7 @@ ohos_unittest("bundle_command_uninstall_test") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -193,6 +200,7 @@ ohos_unittest("bundle_command_uninstall_test") { ] external_deps = [ + "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/tools/test/unittest/bm/bundle_command_install_test.cpp b/tools/test/unittest/bm/bundle_command_install_test.cpp index 482e281c2b1bb16625445c2cf055e84eab7db772..0d77c76c3049df79c2f95eade23a18335ba13248 100644 --- a/tools/test/unittest/bm/bundle_command_install_test.cpp +++ b/tools/test/unittest/bm/bundle_command_install_test.cpp @@ -391,3 +391,55 @@ HWTEST_F(BmCommandInstallTest, Bm_Command_Install_1300, Function | MediumTest | EXPECT_EQ(cmd.ExecCommand(), STRING_INSTALL_BUNDLE_OK + "\n"); } + +/** + * @tc.number: Bm_Command_Install_1400 + * @tc.name: ExecCommand + * @tc.desc: Verify the "bm install -p -f" command. + */ +HWTEST_F(BmCommandInstallTest, Bm_Command_Install_1400, Function | MediumTest | Level1) +{ + // install a bundle + char *argv[] = { + (char *)TOOL_NAME.c_str(), + (char *)cmd_.c_str(), + (char *)"-p", + (char *)STRING_BUNDLE_PATH.c_str(), + (char *)"-f", + (char *)"", + }; + int argc = sizeof(argv) / sizeof(argv[0]) - 1; + + BundleManagerShellCommand cmd(argc, argv); + + // set the mock objects + SetMockObjects(cmd); + + EXPECT_EQ(cmd.ExecCommand(), STRING_INSTALL_BUNDLE_OK + "\n"); +} + +/** + * @tc.number: Bm_Command_Install_1500 + * @tc.name: ExecCommand + * @tc.desc: Verify the "bm install -f -p " command. + */ +HWTEST_F(BmCommandInstallTest, Bm_Command_Install_1500, Function | MediumTest | Level1) +{ + // install a bundle + char *argv[] = { + (char *)TOOL_NAME.c_str(), + (char *)cmd_.c_str(), + (char *)"-f", + (char *)"-p", + (char *)STRING_BUNDLE_PATH.c_str(), + (char *)"", + }; + int argc = sizeof(argv) / sizeof(argv[0]) - 1; + + BundleManagerShellCommand cmd(argc, argv); + + // set the mock objects + SetMockObjects(cmd); + + EXPECT_EQ(cmd.ExecCommand(), STRING_INSTALL_BUNDLE_OK + "\n"); +}