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 1c61dd0eb2cc5dadac420cff1570a51073eafeb0..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") { @@ -26,11 +29,17 @@ ohos_shared_library("appexecfwk_base") { "src/ability_info.cpp", "src/application_info.cpp", "src/bundle_info.cpp", + "src/compatible_ability_info.cpp", + "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 d6e0d5e4edb64f9d24a0a8ffd9b4f01805781a29..1319feedabf0ba61b258b77786e16ef8c658c547 100644 --- a/interfaces/innerkits/appexecfwk_base/include/ability_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/ability_info.h @@ -29,6 +29,12 @@ enum class AbilityType { PAGE, SERVICE, DATA, + FORM, +}; + +enum class AbilitySubType { + UNSPECIFIED = 0, + CA, }; enum class DisplayOrientation { @@ -65,7 +71,76 @@ struct CustomizeData { struct MetaData { std::vector parameters; std::vector results; - std::vector customizeData; + std::vector customizeData; +}; + +struct AbilityInfo; + +/* +* According to Ability profile 1.0 +*/ +struct CompatibleAbilityInfo : public Parcelable { + // deprecated: ability code class simple name, use 'className' instead. + std::string package; + std::string name; + std::string label; // display name on screen. + std::string description; + std::string iconPath; // used as icon data (base64) for WEB Ability. + std::string uri; // uri of ability. + std::string moduleName; // indicates the name of the .hap package to which the capability belongs. + std::string process; + std::string targetAbility; + std::string appName; + std::string privacyUrl; + std::string privacyName; + std::string downloadUrl; + std::string versionName; + uint32_t backgroundModes = 0; + uint32_t packageSize = 0; // The size of the package that AbilityInfo.uri points to. + bool visible = false; + bool formEnabled = false; + bool multiUserShared = false; + // deprecated: remove this field in new package format. + AbilityType type = AbilityType::UNKNOWN; + AbilitySubType subType = AbilitySubType::UNSPECIFIED; + DisplayOrientation orientation = DisplayOrientation::UNSPECIFIED; + LaunchMode launchMode = LaunchMode::STANDARD; + std::vector permissions; + std::vector deviceTypes; + std::vector deviceCapabilities; + bool supportPipMode = false; + bool grantPermission = false; + std::string readPermission; + std::string writePermission; + std::string uriPermissionMode; + std::string uriPermissionPath; + bool directLaunch = true; + + // set when install + std::string bundleName; // bundle name which has this ability. + std::string className; // the ability full class name. + std::string originalClassName; // the original ability full class name + std::string deviceId; // device UDID information. + CompatibleApplicationInfo applicationInfo; + + // form widget info + uint32_t formEntity = 1; // where form can be displayed + int32_t minFormHeight = 0; // minimum height of ability. + int32_t defaultFormHeight = 0; // default height of ability. + int32_t minFormWidth = 0; // minimum width of ability. + int32_t defaultFormWidth = 0; // default width of ability. + + uint32_t iconId = 0; + uint32_t labelId = 0; + uint32_t descriptionId = 0; + bool enabled = true; + + bool ReadFromParcel(Parcel& parcel); + virtual bool Marshalling(Parcel& parcel) const override; + static CompatibleAbilityInfo* Unmarshalling(Parcel& parcel); + + void CopyToDest(CompatibleAbilityInfo& dest) const; + void ConvertToAbilityInfo(AbilityInfo& abilityInfo) const; }; // configuration information about an ability @@ -74,12 +149,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; @@ -91,9 +171,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; - std::vector formEntity; + std::vector configChanges; + uint32_t formEntity; int32_t minFormHeight = 0; int32_t defaultFormHeight = 0; int32_t minFormWidth = 0; @@ -110,12 +193,31 @@ struct AbilityInfo : public Parcelable { std::string resourcePath; // resource path for resource init std::string libPath; // ability library path without name, libPath->libDir + // element that does not exist for a while + std::string originalBundleName; + std::string appName; + std::string privacyUrl; + std::string privacyName; + std::string downloadUrl; + std::string versionName; + std::string className; + std::string originalClassName; + std::string uriPermissionMode; + std::string uriPermissionPath; + uint32_t backgroundModes = 0; + uint32_t packageSize = 0; + bool multiUserShared = false; + bool grantPermission = false; + bool directLaunch = true; + AbilitySubType subType = AbilitySubType::UNSPECIFIED; + bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static AbilityInfo *Unmarshalling(Parcel &parcel); void Dump(std::string prefix, int fd); + void ConvertToCompatiableAbilityInfo(CompatibleAbilityInfo& compatibleAbilityInfo) const; }; } // namespace AppExecFwk } // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_ABILITY_INFO_H +#endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_ABILITY_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h index 6a92a32d0849186db704f1c1da7ccc6fbdcb239d..14ee10d64f7ccf8279f5c000ca18517c6ab17796 100644 --- a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h +++ b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h @@ -19,11 +19,11 @@ #include "errors.h" namespace OHOS { - 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 +103,39 @@ 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_GET_INFO_FAILED, + ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, + ERR_APPEXECFWK_FORM_INVALID_PARAM, + ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, + ERR_APPEXECFWK_FORM_NOT_EXIST_ID, + ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, + ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, + ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, + ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, + ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, + ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, + ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, + 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_MAX_REQUEST, + ERR_APPEXECFWK_FORM_MAX_REFRESH, + ERR_APPEXECFWK_FORM_GET_BMS_FAILED, + + // error code in sdk + ERR_APPEXECFWK_FORM_GET_FMS_FAILED, + ERR_APPEXECFWK_FORM_SEND_FMS_MSG, + ERR_APPEXECFWK_FORM_FORM_DUPLICATE_ADDED, + ERR_APPEXECFWK_FORM_IN_RECOVER, + ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED +}; constexpr ErrCode APPEXECFWK_APPEXECFWK_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, APPEXECFWK_MODULE_APPEXECFWK); enum { ERR_APPEXECFWK_CHECK_FAILED = APPEXECFWK_APPEXECFWK_ERR_OFFSET + 1, @@ -111,4 +144,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 70e02d5fd619400287df6406f253903fa644235a..96168d46265b935e140bcdabcf91798f1f8bb835 100644 --- a/interfaces/innerkits/appexecfwk_base/include/application_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/application_info.h @@ -33,6 +33,37 @@ enum class ApplicationFlag { GET_APPLICATION_INFO_WITH_PERMS = 0x00000008, }; +struct ApplicationInfo; + +struct CompatibleApplicationInfo : public Parcelable { + // items set when installing. + std::string name; // application name. + std::string icon; // application icon resource index. + std::string label; // application name displayed to the user. + std::string description; // description of application. + std::string cpuAbi; // current device cpu abi. + std::string process; + bool isCompressNativeLibs = true; + + uint32_t iconId = 0; + uint32_t labelId = 0; + uint32_t descriptionId = 0; + + bool systemApp = false; + + std::vector permissions; + std::vector moduleInfos; + + uint32_t supportedModes = 0; // supported modes. + bool enabled = true; + bool debug = false; + + bool ReadFromParcel(Parcel& parcel); + virtual bool Marshalling(Parcel& parcel) const override; + static CompatibleApplicationInfo* Unmarshalling(Parcel& parcel); + void ConvertToApplicationInfo(ApplicationInfo& applicationInfo) const; +}; + // configuration information about an application struct ApplicationInfo : public Parcelable { std::string name; // application name is same to bundleName @@ -59,11 +90,20 @@ struct ApplicationInfo : public Parcelable { std::string cacheDir; int flags = 0; bool enabled = false; + + // element that does not exist for a while + std::string entryModuleName; + std::string icon; + std::string cpuAbi; + bool isCompressNativeLibs = true; + bool debug = false; + bool systemApp = false; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static ApplicationInfo *Unmarshalling(Parcel &parcel); void Dump(std::string prefix, int fd); + void ConvertToCompatibleApplicationInfo(CompatibleApplicationInfo& compatibleApplicationInfo) const; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h b/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h index b65bf54f182b44e8941ce3eda810205ce870bd95..0a5a4207d82f930808f93fcbac1a05908fc855f9 100755 --- a/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h +++ b/interfaces/innerkits/appexecfwk_base/include/bundle_constants.h @@ -112,10 +112,20 @@ 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 = '/'; + +const int MAX_DIMENSION_SIZE = 10; +const int MAX_DEVICETYPE_SIZE = 50; + } // namespace Constants } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/include/bundle_info.h b/interfaces/innerkits/appexecfwk_base/include/bundle_info.h index 04b4919ca571a4174251aed8b7b90aded4f636b7..a4c798440e52baf4fe746fd8b3597d85b384905b 100644 --- a/interfaces/innerkits/appexecfwk_base/include/bundle_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/bundle_info.h @@ -23,6 +23,7 @@ #include "ability_info.h" #include "application_info.h" +#include "hap_module_info.h" namespace OHOS { namespace AppExecFwk { @@ -66,6 +67,7 @@ struct BundleInfo : public Parcelable { // update time is the same as the installation time. ApplicationInfo applicationInfo; std::vector abilityInfos; + std::vector hapModuleInfos; std::vector reqPermissions; std::vector defPermissions; // the permissions required for accessing the application. std::vector hapModuleNames; // the "module.package" in each config.json 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_info.h b/interfaces/innerkits/appexecfwk_base/include/form_info.h index 3b28190c973c738895925a1275ea296b91e4cffd..6048620d7fdef30262521fe34f478edfa0d02528 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_info.h @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - enum class FormsColorMode { AUTO_MODE = -1, DARK_MODE = 0, @@ -68,7 +67,6 @@ struct FormInfo : public Parcelable { virtual bool Marshalling(Parcel &parcel) const override; static FormInfo *Unmarshalling(Parcel &parcel); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_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..69fe4a021719e38faa95ac9154e7ac1929348bd5 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_js_info.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_OHOS_FORM_JS_INFO_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_JS_INFO_H + + +#include +#include "parcel.h" +#include "form_provider_data.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; + FormProviderData formProviderData; + + 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..e23be681025b11ab529ab0704d1c407fed8655ec --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h @@ -0,0 +1,164 @@ +/* + * 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 + +#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..522b8584d0550a395022032aa42dd9a85c6d93f6 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h @@ -0,0 +1,98 @@ +/* + * 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 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: + FormProviderData jsBindingData_; + bool upgradeFlg_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H diff --git a/interfaces/innerkits/appexecfwk_base/include/hap_module_info.h b/interfaces/innerkits/appexecfwk_base/include/hap_module_info.h index 29568df009c570c4a8964490bf8e07015226f06e..25b25d6599894c9fc35a8b21199e1c446ec70223 100644 --- a/interfaces/innerkits/appexecfwk_base/include/hap_module_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/hap_module_info.h @@ -24,7 +24,7 @@ namespace OHOS { namespace AppExecFwk { -enum class ModuleColorMode{ +enum class ModuleColorMode { AUTO = -1, DARK, LIGHT, @@ -38,6 +38,7 @@ struct HapModuleInfo : public Parcelable { std::string iconPath; std::string label; std::string backgroundImg; + std::string mainAbility; int supportedModes = 0; std::vector reqCapabilities; 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 af6ac77a971962286a2c91f33a3c2afc4448f34b..a386208e35dafd4ed6e0d5cf351fa9dd28e17c85 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,7 +75,12 @@ 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"; +const std::string JSON_KEY_SRC_PATH = "srcPath"; +const std::string JSON_KEY_SRC_LANGUAGE = "srcLanguage"; } // namespace bool AbilityInfo::ReadFromParcel(Parcel &parcel) @@ -97,20 +104,27 @@ bool AbilityInfo::ReadFromParcel(Parcel &parcel) targetAbility = Str16ToStr8(parcel.ReadString16()); readPermission = Str16ToStr8(parcel.ReadString16()); writePermission = Str16ToStr8(parcel.ReadString16()); + srcPath = Str16ToStr8(parcel.ReadString16()); + srcLanguage = Str16ToStr8(parcel.ReadString16()); visible = parcel.ReadBool(); isLauncherAbility = parcel.ReadBool(); isNativeAbility = parcel.ReadBool(); enabled = parcel.ReadBool(); - - int32_t formEntitySize; - READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, formEntitySize); - for (int32_t i = 0; i < formEntitySize; i++) { - formEntity.emplace_back(Str16ToStr8(parcel.ReadString16())); + 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,18 +236,26 @@ bool AbilityInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(targetAbility)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(readPermission)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(writePermission)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcPath)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcLanguage)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, visible); 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(Int32, parcel, formEntity.size()); - for (auto &item : formEntity) { - WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(item)); + 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)); @@ -293,8 +315,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); @@ -309,7 +332,7 @@ void AbilityInfo::Dump(std::string prefix, int fd) void to_json(nlohmann::json &jsonObject, const Parameters ¶meters) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {JSON_KEY_DESCRIPTION, parameters.description}, {JSON_KEY_NAME, parameters.name}, {JSON_KEY_TYPE, parameters.type} @@ -318,7 +341,7 @@ void to_json(nlohmann::json &jsonObject, const Parameters ¶meters) void to_json(nlohmann::json &jsonObject, const Results &results) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {JSON_KEY_DESCRIPTION, results.description}, {JSON_KEY_NAME, results.name}, {JSON_KEY_TYPE, results.type} @@ -327,7 +350,7 @@ void to_json(nlohmann::json &jsonObject, const Results &results) void to_json(nlohmann::json &jsonObject, const CustomizeData &customizeData) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {JSON_KEY_NAME, customizeData.name}, {JSON_KEY_META_VALUE, customizeData.value}, {JSON_KEY_META_EXTRA, customizeData.extra} @@ -336,7 +359,7 @@ void to_json(nlohmann::json &jsonObject, const CustomizeData &customizeData) void to_json(nlohmann::json &jsonObject, const MetaData &metaData) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {JSON_KEY_PARAMETERS, metaData.parameters}, {JSON_KEY_RESULTS, metaData.results}, {JSON_KEY_CUSTOMIZE_DATA, metaData.customizeData} @@ -345,7 +368,8 @@ void to_json(nlohmann::json &jsonObject, const MetaData &metaData) void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo) { - jsonObject = nlohmann::json{{JSON_KEY_NAME, abilityInfo.name}, + jsonObject = nlohmann::json { + {JSON_KEY_NAME, abilityInfo.name}, {JSON_KEY_LABEL, abilityInfo.label}, {JSON_KEY_DESCRIPTION, abilityInfo.description}, {JSON_KEY_ICON_PATH, abilityInfo.iconPath}, @@ -354,13 +378,20 @@ 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_SRC_PATH, abilityInfo.srcPath}, + {JSON_KEY_SRC_LANGUAGE, abilityInfo.srcLanguage}, + {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}, @@ -379,7 +410,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} }; } @@ -422,13 +454,20 @@ 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.formEntity = jsonObject.at(JSON_KEY_FORM_ENTITY).get>(); + abilityInfo.srcPath = jsonObject.at(JSON_KEY_SRC_PATH).get(); + abilityInfo.srcLanguage = jsonObject.at(JSON_KEY_SRC_LANGUAGE).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(); @@ -448,7 +487,62 @@ 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 +{ + APP_LOGE("AbilityInfo::ConvertToCompatiableAbilityInfo called"); + compatibleAbilityInfo.package = package; + compatibleAbilityInfo.name = name; + compatibleAbilityInfo.label = label; + compatibleAbilityInfo.description = description; + compatibleAbilityInfo.iconPath = iconPath; + compatibleAbilityInfo.uri = uri; + compatibleAbilityInfo.moduleName = moduleName; + compatibleAbilityInfo.process = process; + compatibleAbilityInfo.targetAbility = targetAbility; + compatibleAbilityInfo.appName = appName; + compatibleAbilityInfo.privacyUrl = privacyUrl; + compatibleAbilityInfo.privacyName = privacyName; + compatibleAbilityInfo.downloadUrl = downloadUrl; + compatibleAbilityInfo.versionName = versionName; + compatibleAbilityInfo.backgroundModes = backgroundModes; + compatibleAbilityInfo.packageSize = packageSize; + compatibleAbilityInfo.visible = visible; + compatibleAbilityInfo.formEnabled = formEnabled; + compatibleAbilityInfo.multiUserShared = multiUserShared; + compatibleAbilityInfo.type = type; + compatibleAbilityInfo.subType = subType; + compatibleAbilityInfo.orientation = orientation; + compatibleAbilityInfo.launchMode = launchMode; + compatibleAbilityInfo.permissions = permissions; + compatibleAbilityInfo.deviceTypes = deviceTypes; + compatibleAbilityInfo.deviceCapabilities = deviceCapabilities; + compatibleAbilityInfo.supportPipMode = supportPipMode; + compatibleAbilityInfo.grantPermission = grantPermission; + compatibleAbilityInfo.readPermission = readPermission; + compatibleAbilityInfo.writePermission = writePermission; + compatibleAbilityInfo.uriPermissionMode = uriPermissionMode; + compatibleAbilityInfo.uriPermissionPath = uriPermissionPath; + compatibleAbilityInfo.directLaunch = directLaunch; + compatibleAbilityInfo.bundleName = bundleName; + compatibleAbilityInfo.className = className; + compatibleAbilityInfo.originalClassName = originalClassName; + compatibleAbilityInfo.deviceId = deviceId; + CompatibleApplicationInfo convertedCompatibleApplicationInfo; + applicationInfo.ConvertToCompatibleApplicationInfo(convertedCompatibleApplicationInfo); + compatibleAbilityInfo.applicationInfo = convertedCompatibleApplicationInfo; + compatibleAbilityInfo.formEntity = formEntity; + compatibleAbilityInfo.minFormHeight = minFormHeight; + compatibleAbilityInfo.defaultFormHeight = defaultFormHeight; + compatibleAbilityInfo.minFormWidth = minFormWidth; + compatibleAbilityInfo.defaultFormWidth = defaultFormWidth; + compatibleAbilityInfo.iconId = iconId; + compatibleAbilityInfo.labelId = labelId; + compatibleAbilityInfo.descriptionId = descriptionId; + compatibleAbilityInfo.enabled = enabled; } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/application_info.cpp b/interfaces/innerkits/appexecfwk_base/src/application_info.cpp index 9f8404cd0a1a02f644c84e7598bf0bec27f486c0..41ba13b3306eb06019a6bf43d7319c9b5fa1c5c3 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); @@ -214,5 +215,25 @@ void from_json(const nlohmann::json &jsonObject, ApplicationInfo &applicationInf applicationInfo.flags = jsonObject.at("flags").get(); } +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 = enabled; +} + } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp b/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp index a0356c00a6db85d3a4740ba751ec02112ce2909b..21a4cf214586ea002b3418df221c04a3678177d0 100644 --- a/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/bundle_info.cpp @@ -109,6 +109,16 @@ bool BundleInfo::ReadFromParcel(Parcel &parcel) } abilityInfos.emplace_back(*abilityInfo); } + + int32_t hapModuleInfosSize = parcel.ReadInt32(); + for (int32_t i = 0; i < hapModuleInfosSize; i++) { + std::unique_ptr hapModuleInfo(parcel.ReadParcelable()); + if (!hapModuleInfo) { + APP_LOGE("ReadParcelable failed"); + return false; + } + hapModuleInfos.emplace_back(*hapModuleInfo); + } return true; } @@ -180,6 +190,11 @@ bool BundleInfo::Marshalling(Parcel &parcel) const for (auto &abilityInfo : abilityInfos) { WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Parcelable, parcel, &abilityInfo); } + + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, hapModuleInfos.size()); + for (auto &hapModuleInfo : hapModuleInfos) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Parcelable, parcel, &hapModuleInfo); + } return true; } diff --git a/interfaces/innerkits/appexecfwk_base/src/compatible_ability_info.cpp b/interfaces/innerkits/appexecfwk_base/src/compatible_ability_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..addc09f02460d2b7433b41da9d2782549292987b --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/compatible_ability_info.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 "ability_info.h" + +#include "nlohmann/json.hpp" + +#include "string_ex.h" + +#include "app_log_wrapper.h" +#include "bundle_constants.h" +#include "parcel_macro.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace Constants; + +bool CompatibleAbilityInfo::ReadFromParcel(Parcel& parcel) +{ + APP_LOGD("CompatibleAbilityInfo::ReadFromParcel called"); + package = Str16ToStr8(parcel.ReadString16()); + name = Str16ToStr8(parcel.ReadString16()); + originalClassName = Str16ToStr8(parcel.ReadString16()); + label = Str16ToStr8(parcel.ReadString16()); + description = Str16ToStr8(parcel.ReadString16()); + iconPath = Str16ToStr8(parcel.ReadString16()); + uri = Str16ToStr8(parcel.ReadString16()); + moduleName = Str16ToStr8(parcel.ReadString16()); + process = Str16ToStr8(parcel.ReadString16()); + targetAbility = Str16ToStr8(parcel.ReadString16()); + appName = Str16ToStr8(parcel.ReadString16()); + privacyUrl = Str16ToStr8(parcel.ReadString16()); + privacyName = Str16ToStr8(parcel.ReadString16()); + downloadUrl = Str16ToStr8(parcel.ReadString16()); + versionName = Str16ToStr8(parcel.ReadString16()); + backgroundModes = parcel.ReadInt32(); + packageSize = parcel.ReadInt32(); + visible = parcel.ReadBool(); + formEnabled = parcel.ReadBool(); + multiUserShared = parcel.ReadBool(); + + int32_t typeData; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, typeData); + type = static_cast(typeData); + + int32_t orientationData; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, orientationData); + orientation = static_cast(orientationData); + + int32_t launchModeData; + 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()); + writePermission = Str16ToStr8(parcel.ReadString16()); + uriPermissionMode = Str16ToStr8(parcel.ReadString16()); + uriPermissionPath = Str16ToStr8(parcel.ReadString16()); + directLaunch = parcel.ReadBool(); + 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(); + minFormWidth = parcel.ReadInt32(); + defaultFormWidth = parcel.ReadInt32(); + iconId = parcel.ReadInt32(); + descriptionId = parcel.ReadInt32(); + labelId = parcel.ReadInt32(); + enabled = parcel.ReadBool(); + return true; +} + +CompatibleAbilityInfo* CompatibleAbilityInfo::Unmarshalling(Parcel& parcel) +{ + APP_LOGD("CompatibleAbilityInfo::Unmarshalling called"); + CompatibleAbilityInfo* info = new CompatibleAbilityInfo(); + if (!info->ReadFromParcel(parcel)) { + APP_LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +bool CompatibleAbilityInfo::Marshalling(Parcel& parcel) const +{ + APP_LOGD("CompatibleAbilityInfo::Marshalling called"); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(package)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(name)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(originalClassName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(label)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(description)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(iconPath)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(uri)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(moduleName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(process)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(targetAbility)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(appName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(privacyUrl)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(privacyName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(downloadUrl)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(versionName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, backgroundModes); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, packageSize); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, visible); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, formEnabled); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, multiUserShared); + 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)); + 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])); + } + 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])); + } + 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)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(writePermission)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(uriPermissionMode)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(uriPermissionPath)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, directLaunch); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(bundleName)); + 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); + 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, iconId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, descriptionId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, labelId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, enabled); + return true; +} + +void CompatibleAbilityInfo::ConvertToAbilityInfo(AbilityInfo& abilityInfo) const +{ + APP_LOGD("CompatibleAbilityInfo::ConvertToAbilityInfo called"); + abilityInfo.package = package; + abilityInfo.name = name; + abilityInfo.label = label; + abilityInfo.description = description; + abilityInfo.iconPath = iconPath; + abilityInfo.uri = uri; + abilityInfo.moduleName = moduleName; + abilityInfo.process = process; + abilityInfo.targetAbility = targetAbility; + abilityInfo.appName = appName; + abilityInfo.privacyUrl = privacyUrl; + abilityInfo.privacyName = privacyName; + abilityInfo.downloadUrl = downloadUrl; + abilityInfo.versionName = versionName; + abilityInfo.backgroundModes = backgroundModes; + abilityInfo.packageSize = packageSize; + abilityInfo.visible = visible; + abilityInfo.formEnabled = formEnabled; + abilityInfo.multiUserShared = multiUserShared; + abilityInfo.type = type; + abilityInfo.subType = subType; + abilityInfo.orientation = orientation; + abilityInfo.launchMode = launchMode; + abilityInfo.permissions = permissions; + abilityInfo.deviceTypes = deviceTypes; + abilityInfo.deviceCapabilities = deviceCapabilities; + abilityInfo.supportPipMode = supportPipMode; + abilityInfo.grantPermission = grantPermission; + abilityInfo.readPermission = readPermission; + abilityInfo.writePermission = writePermission; + abilityInfo.uriPermissionMode = uriPermissionMode; + abilityInfo.uriPermissionPath = uriPermissionPath; + abilityInfo.directLaunch = directLaunch; + abilityInfo.bundleName = bundleName; + abilityInfo.className = className; + abilityInfo.originalClassName = originalClassName; + abilityInfo.deviceId = deviceId; + ApplicationInfo convertedApplicationInfo; + applicationInfo.ConvertToApplicationInfo(convertedApplicationInfo); + abilityInfo.applicationInfo = convertedApplicationInfo; + abilityInfo.formEntity = formEntity; + abilityInfo.minFormHeight = minFormHeight; + abilityInfo.defaultFormHeight = defaultFormHeight; + abilityInfo.minFormWidth = minFormWidth; + abilityInfo.defaultFormWidth = defaultFormWidth; + abilityInfo.iconId = iconId; + abilityInfo.labelId = labelId; + abilityInfo.descriptionId = descriptionId; + abilityInfo.enabled = enabled; + abilityInfo.originalBundleName = bundleName; + +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/compatible_application_info.cpp b/interfaces/innerkits/appexecfwk_base/src/compatible_application_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2dbafedab7a2e90e67deb937e4168b392814b75 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/compatible_application_info.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 "application_info.h" + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +#include "string_ex.h" +#include "app_log_wrapper.h" +#include "bundle_constants.h" +#include "parcel_macro.h" +#include "json_serializer.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace Constants; + +namespace { + const std::string DEBUG = "debug"; +} // namespace + +bool CompatibleApplicationInfo::ReadFromParcel(Parcel& parcel) +{ + APP_LOGD("CompatibleApplicationInfo::ReadFromParcel called"); + name = Str16ToStr8(parcel.ReadString16()); + icon = Str16ToStr8(parcel.ReadString16()); + label = Str16ToStr8(parcel.ReadString16()); + description = Str16ToStr8(parcel.ReadString16()); + cpuAbi = Str16ToStr8(parcel.ReadString16()); + process = Str16ToStr8(parcel.ReadString16()); + systemApp = parcel.ReadBool(); + supportedModes = parcel.ReadInt32(); + iconId = parcel.ReadInt32(); + descriptionId = parcel.ReadInt32(); + labelId = parcel.ReadInt32(); + isCompressNativeLibs = parcel.ReadBool(); + + int32_t permissionSize; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, permissionSize); + if (permissionSize > Constants::MAX_LIMIT_SIZE) { + APP_LOGE("permissions size is overflow"); + return false; + } + for (auto i = 0; i < permissionSize; i++) { + std::string permission = Str16ToStr8(parcel.ReadString16()); + if (permission.empty()) { + APP_LOGE("ReadParcelable failed"); + return false; + } + permissions.emplace_back(permission); + } + + int32_t moduleInfoSize; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, moduleInfoSize); + if (moduleInfoSize > Constants::MAX_LIMIT_SIZE) { + APP_LOGE("module info size is overflow"); + return false; + } + for (auto i = 0; i < moduleInfoSize; i++) { + ModuleInfo moduleInfo; + std::string moduleName = Str16ToStr8(parcel.ReadString16()); + std::string moduleSourceDir = Str16ToStr8(parcel.ReadString16()); + if (moduleName.empty() || moduleSourceDir.empty()) { + APP_LOGE("ReadParcelable failed"); + return false; + } + moduleInfo.moduleName = moduleName; + moduleInfo.moduleSourceDir = moduleSourceDir; + moduleInfos.emplace_back(moduleInfo); + } + enabled = parcel.ReadBool(); + debug = parcel.ReadBool(); + return true; +} + +CompatibleApplicationInfo* CompatibleApplicationInfo::Unmarshalling(Parcel& parcel) +{ + APP_LOGD("CompatibleApplicationInfo::Unmarshalling called"); + CompatibleApplicationInfo* info = new CompatibleApplicationInfo(); + if (info && !info->ReadFromParcel(parcel)) { + APP_LOGW("read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +bool CompatibleApplicationInfo::Marshalling(Parcel& parcel) const +{ + APP_LOGD("CompatibleApplicationInfo::Marshalling called"); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(name)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(icon)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(label)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(description)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(cpuAbi)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(process)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, systemApp); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, supportedModes); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, iconId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, descriptionId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, labelId); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isCompressNativeLibs); + const auto permissionSize = static_cast(permissions.size()); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, permissionSize); + for (auto i = 0; i < permissionSize; i++) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(permissions[i])); + } + const auto moduleInfoSize = static_cast(moduleInfos.size()); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, moduleInfoSize); + for (auto i = 0; i < moduleInfoSize; i++) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(moduleInfos[i].moduleName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(moduleInfos[i].moduleSourceDir)); + } + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, enabled); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, debug); + + return true; +} + +void CompatibleApplicationInfo::ConvertToApplicationInfo(ApplicationInfo& applicationInfo) const +{ + APP_LOGD("CompatibleApplicationInfo::ConvertToApplicationInfo called"); + applicationInfo.name = name; + applicationInfo.icon = icon; + applicationInfo.label = label; + applicationInfo.description = description; + applicationInfo.cpuAbi = cpuAbi; + applicationInfo.process = process; + applicationInfo.systemApp = systemApp; + applicationInfo.isCompressNativeLibs = isCompressNativeLibs; + applicationInfo.iconId = iconId; + applicationInfo.labelId = labelId; + applicationInfo.descriptionId = descriptionId; + applicationInfo.permissions = permissions; + applicationInfo.moduleInfos = moduleInfos; + applicationInfo.supportedModes = supportedModes; + applicationInfo.enabled = debug; + applicationInfo.entryModuleName = ""; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp index 7f9f1d2e23f69f72ba35bea6f63113f9640b9d23..9e589c283d149557e8d2057d85149b45ba129780 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp @@ -29,9 +29,7 @@ namespace OHOS { namespace AppExecFwk { - namespace { - const std::string JSON_KEY_COLOR_MODE = "colorMode"; const std::string JSON_KEY_PACKAGE = "package"; const std::string JSON_KEY_SUPPORT_DIMENSIONS = "supportDimensions"; @@ -57,7 +55,6 @@ const std::string JSON_KEY_FORM_VISIBLE_NOTIFY = "formVisibleNotify"; const std::string JSON_KEY_RELATED_BUNDLE_NAME = "relatedBundleName"; const std::string JSON_KEY_DEFAULT_FLAG = "defaultFlag"; const std::string JSON_KEY_PORTRAIT_LAYOUTS = "portraitLayouts"; - } // namespace bool FormInfo::ReadFromParcel(Parcel &parcel) @@ -184,12 +181,16 @@ bool FormInfo::Marshalling(Parcel &parcel) const void to_json(nlohmann::json &jsonObject, const FormCustomizeData &customizeDatas) { - jsonObject = nlohmann::json{{JSON_KEY_NAME, customizeDatas.name}, {JSON_KEY_VALUE, customizeDatas.value}}; + jsonObject = nlohmann::json{ + {JSON_KEY_NAME, customizeDatas.name}, + {JSON_KEY_VALUE, customizeDatas.value} + }; } void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) { - jsonObject = nlohmann::json{{JSON_KEY_NAME, formInfo.name}, + jsonObject = nlohmann::json{ + {JSON_KEY_NAME, formInfo.name}, {JSON_KEY_PACKAGE, formInfo.package}, {JSON_KEY_BUNDLE_NAME, formInfo.bundleName}, {JSON_KEY_MODULE_NAME, formInfo.moduleName}, @@ -212,7 +213,8 @@ void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) {JSON_KEY_SUPPORT_DIMENSIONS, formInfo.supportDimensions}, {JSON_KEY_CUSTOMIZE_DATA, formInfo.customizeDatas}, {JSON_KEY_LANDSCAPE_LAYOUTS, formInfo.landscapeLayouts}, - {JSON_KEY_PORTRAIT_LAYOUTS, formInfo.portraitLayouts}}; + {JSON_KEY_PORTRAIT_LAYOUTS, formInfo.portraitLayouts} + }; } void from_json(const nlohmann::json &jsonObject, FormCustomizeData &customizeDatas) @@ -248,6 +250,5 @@ void from_json(const nlohmann::json &jsonObject, FormInfo &formInfo) formInfo.landscapeLayouts = jsonObject.at(JSON_KEY_LANDSCAPE_LAYOUTS).get>(); formInfo.portraitLayouts = jsonObject.at(JSON_KEY_PORTRAIT_LAYOUTS).get>(); } - } // 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..13a5d3c2684590d10ba36156844b6dda4c35fd5b --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp @@ -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. + */ + +#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()); + + auto bindingData = parcel.ReadParcelable(); + formProviderData = *bindingData; + if (nullptr == bindingData){ + return false; + } + 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; + } + + // write formProviderData + if (!parcel.WriteParcelable(&formProviderData)) { + 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..918a832f4048055e3191ddb7def4be7bb65e4648 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp @@ -0,0 +1,324 @@ +/* + * 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 "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; +const std::string JSON_EMPTY_STRING = "{}"; + +/** + * @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) +{ + if(jsonDataString.empty()) { + jsonDataString = JSON_EMPTY_STRING; + } + 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__); + std::string dataStr = jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); + APP_LOGI("%{public}s, data: %{public}s", __func__, dataStr.c_str()); + return dataStr; +} + +/** + * @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__); + if(jsonDataString.empty()) { + jsonDataString = JSON_EMPTY_STRING; + } + 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 && [key, value] : addJsonData.items()) { + jsonFormProviderData_[key] = 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())); + + 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, jsonFormProviderData_: %{public}s", __func__, jsonFormProviderData_.dump().c_str()); + if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? JSON_EMPTY_STRING : jsonFormProviderData_.dump()))) { + return false; + } + + 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; + } + std::string str = formProviderData->GetDataString(); + APP_LOGI("%{public}s, , provider data length: %{public}zu, provider data: %{public}s", __func__, str.length(), str.c_str()); + 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..d6b83c82a9d2ba74296b33b3f7f157e93523eec5 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp @@ -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. + */ + +#include "form_provider_info.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool FormProviderInfo::ReadFromParcel(Parcel &parcel) +{ + 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.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/hap_module_info.cpp b/interfaces/innerkits/appexecfwk_base/src/hap_module_info.cpp index e1437ccd526790d0174c229718b44d950bfcd5ef..55c0184a3c834504b35dc0e32477222d92b92107 100644 --- a/interfaces/innerkits/appexecfwk_base/src/hap_module_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/hap_module_info.cpp @@ -32,6 +32,7 @@ bool HapModuleInfo::ReadFromParcel(Parcel &parcel) iconPath = Str16ToStr8(parcel.ReadString16()); label = Str16ToStr8(parcel.ReadString16()); backgroundImg = Str16ToStr8(parcel.ReadString16()); + mainAbility = Str16ToStr8(parcel.ReadString16()); supportedModes = parcel.ReadInt32(); int32_t reqCapabilitiesSize; @@ -81,6 +82,7 @@ bool HapModuleInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(iconPath)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(label)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(backgroundImg)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(mainAbility)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, supportedModes); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, reqCapabilities.size()); for (auto &reqCapability : reqCapabilities) { 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_info.cpp b/interfaces/innerkits/appexecfwk_base/src/module_info.cpp index 9c7e51b030eaa401719a3da91ad3e7a929149a0d..af25a74eeac695f05dac1a3a77ea83f5db518af6 100644 --- a/interfaces/innerkits/appexecfwk_base/src/module_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/module_info.cpp @@ -51,7 +51,7 @@ bool ModuleInfo::Marshalling(Parcel &parcel) const void to_json(nlohmann::json &jsonObject, const ModuleInfo &moduleInfo) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {"moduleName", moduleInfo.moduleName}, {"moduleSourceDir", moduleInfo.moduleSourceDir} }; 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..3ac88d068885906ffefa12f99f71cec9158986a6 --- /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 \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/shortcut_info.cpp b/interfaces/innerkits/appexecfwk_base/src/shortcut_info.cpp index 533fcb542ce06eab67bcda8704d7055acb610474..84943ba10ebab72c5bd629ba5dd4c2cf7b55570d 100644 --- a/interfaces/innerkits/appexecfwk_base/src/shortcut_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/shortcut_info.cpp @@ -104,13 +104,15 @@ bool ShortcutInfo::Marshalling(Parcel &parcel) const void to_json(nlohmann::json &jsonObject, const ShortcutIntent &shortcutIntent) { - jsonObject = nlohmann::json{{JSON_KEY_BUNDLE_TARGET_BUNDLE, shortcutIntent.targetBundle}, + jsonObject = nlohmann::json { + {JSON_KEY_BUNDLE_TARGET_BUNDLE, shortcutIntent.targetBundle}, {JSON_KEY_BUNDLE_TARGET_CLASS, shortcutIntent.targetClass}}; } void to_json(nlohmann::json &jsonObject, const ShortcutInfo &shortcutInfo) { - jsonObject = nlohmann::json{{JSON_KEY_BUNDLE_ID, shortcutInfo.id}, + jsonObject = nlohmann::json { + {JSON_KEY_BUNDLE_ID, shortcutInfo.id}, {JSON_KEY_BUNDLE_NAME, shortcutInfo.bundleName}, {JSON_KEY_BUNDLE_HOST_ABILITY, shortcutInfo.hostAbility}, {JSON_KEY_BUNDLE_ICON, shortcutInfo.icon}, 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/ams_mgr_interface.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_interface.h index 5de610a3b3db147f58aa232369ac394fe348e054..5572cac4e0227b1d5851bb4336f725433e6cdd31 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_interface.h @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { - class IAmsMgr : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IAmsMgr"); @@ -133,7 +132,6 @@ public: AMS_COMPEL_VERIFY_PERMISSION, }; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h index 656fba6238f7ff2fc8c7c78400b204e53d1b31cd..086a8ad5c1d232cd68f919f111b3e81aac957e59 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_proxy.h @@ -22,7 +22,6 @@ namespace OHOS { namespace AppExecFwk { - class AmsMgrProxy : public IRemoteProxy { public: explicit AmsMgrProxy(const sptr &impl); @@ -123,7 +122,6 @@ private: private: static inline BrokerDelegator delegator_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_CLIENT_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h index 34450915bdcb0f18f4dd338b8d2b83033aae20db..a5e9874ad892a53b0f4a904fd16fe382be216f9e 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/ams_mgr_stub.h @@ -25,7 +25,6 @@ namespace OHOS { namespace AppExecFwk { - class AmsMgrStub : public IRemoteStub { public: AmsMgrStub(); @@ -51,7 +50,6 @@ private: DISALLOW_COPY_AND_MOVE(AmsMgrStub); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_AMS_MGR_STUB_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_launch_data.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_launch_data.h index b65b80abd4279d43db932c5973c1c0e1dab33c3e..a94a8bbd4b06f671b875c12c9ca30309a06df122 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_launch_data.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_launch_data.h @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { - class AppLaunchData : public Parcelable { public: /** @@ -143,7 +142,6 @@ private: int32_t recordId_ = 0; int32_t uId_ = 0; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_APPMGR_INCLUDE_APP_LAUNCH_DATA_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h index 323d60501e5e5be18024aee28722f2903cee5b9f..55bf0be769e6fac1defce4874f8fe6ffdb019b64 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_client.h @@ -27,7 +27,6 @@ namespace OHOS { namespace AppExecFwk { - class AppServiceManager; class AppMgrClient { @@ -173,7 +172,6 @@ private: std::unique_ptr serviceManager_; sptr remote_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_MGR_CLIENT_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h index 3ec06f155c15c43b98f2aed7793d1a5d14bb047f..eedab3f61957910c462a4a1e17b50ed2caad3aad 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_constants.h @@ -19,9 +19,7 @@ namespace OHOS { namespace AppExecFwk { namespace Constants { - const std::string APP_MGR_SERVICE_NAME = "AppMgrService"; - } // namespace Constants enum class ApplicationState { @@ -50,7 +48,6 @@ enum AppMgrResultCode { ERROR_SERVICE_NOT_READY, ERROR_SERVICE_NOT_CONNECTED, }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CONSTANTS_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h index 766e8d23f2b4e0fb3e55e65ecb9d40f2be98e896..d6a380253a8f2361adf357e8f5f780a348c9873b 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_interface.h @@ -28,7 +28,6 @@ namespace OHOS { namespace AppExecFwk { - class IAppMgr : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AppMgr"); @@ -153,7 +152,6 @@ public: AMS_APP_GET_APP_FREEZING_TIME, }; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h index 8d48bb48b00ea86bd0daa15624813cb9585c25e1..e71ef18f250a8c2aa8e2638e59d15a7708985258 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_proxy.h @@ -22,7 +22,6 @@ namespace OHOS { namespace AppExecFwk { - class AppMgrProxy : public IRemoteProxy { public: explicit AppMgrProxy(const sptr &impl); @@ -136,11 +135,10 @@ public: private: bool SendTransactCmd(IAppMgr::Message code, MessageParcel &data, MessageParcel &reply); bool WriteInterfaceToken(MessageParcel &data); - template + template int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); static inline BrokerDelegator delegator_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_CLIENT_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h index b71636866b3443ce2655524df0a51f5983bc4c21..094e29ec3bd16c800cc7f4e42b6022efec401748 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_mgr_stub.h @@ -25,7 +25,6 @@ namespace OHOS { namespace AppExecFwk { - class AppMgrStub : public IRemoteStub { public: AppMgrStub(); @@ -53,7 +52,6 @@ private: DISALLOW_COPY_AND_MOVE(AppMgrStub); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_MGR_STUB_H 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..48e3a991ad500f127deffc4b100643c8b530062c 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_process_data.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_process_data.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - struct AppProcessData : public Parcelable { /** * @brief read this Sequenceable object from a Parcel. @@ -52,8 +51,8 @@ struct AppProcessData : public Parcelable { std::string processName; ApplicationState appState = ApplicationState::APP_STATE_CREATE; pid_t pid = 0; + int32_t uid = 0; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_PROCESS_DATA_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_record_id.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_record_id.h index fa9303e7eb0d65faa19190359b33dcc9ee60f62d..2a9bd3157421fdd273aa09805c151e8d35ec5567 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_record_id.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_record_id.h @@ -18,7 +18,6 @@ namespace OHOS { namespace AppExecFwk { - class AppRecordId { public: /** @@ -28,7 +27,6 @@ public: */ static int32_t Create(); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_RECORD_ID_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_interface.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_interface.h index 1f1799b74d4d790d490e4c903a65567b1b3f3718..1a03aeb9c26488983ac9c9080ce4647b886bda47 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_interface.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_interface.h @@ -138,7 +138,6 @@ public: SCHEDULE_PROCESS_SECURITY_EXIT_TRANSACTION, }; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_INTERFACE_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_proxy.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_proxy.h index a9050822421d700c0f75aee94d9bd7dcd1234cb8..81647d7dd9f61bf4571b269eca004f76d5b1f770 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_scheduler_proxy.h @@ -126,7 +126,6 @@ private: bool WriteInterfaceToken(MessageParcel &data); static inline BrokerDelegator delegator_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_SCHEDULER_CLIENT_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_service_manager.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_service_manager.h index 6cca44e0604267c891ba54dec740983768d0e14e..fae5e8ea79255ac52d02ebf69a30d2ac9e276472 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_service_manager.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_service_manager.h @@ -20,7 +20,6 @@ namespace OHOS { namespace AppExecFwk { - class AppServiceManager { public: AppServiceManager() = default; @@ -33,7 +32,6 @@ public: */ virtual sptr GetAppMgrService() const; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APP_SERVICE_MANAGER_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_host.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_host.h index 0c4ce2bb6d72ec1a3ba3f16261df56fbfa0efae8..eec80b877474bf1edc0d1bf794a76daaf4f5c7db 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_host.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_host.h @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { - class AppStateCallbackHost : public IRemoteStub { public: AppStateCallbackHost(); @@ -59,7 +58,6 @@ private: DISALLOW_COPY_AND_MOVE(AppStateCallbackHost); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_HOST_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_proxy.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_proxy.h index f563c110fb2168858b57bf85eaade11fcbf4171b..b91ed58a3445f533dd1ef3a1a10b259c39c1ab88 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_proxy.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_state_callback_proxy.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class AppStateCallbackProxy : public IRemoteProxy { public: explicit AppStateCallbackProxy(const sptr &impl); @@ -48,7 +47,6 @@ private: bool WriteInterfaceToken(MessageParcel &data); static inline BrokerDelegator delegator_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_STATE_CALLBACK_PROXY_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_task_info.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_task_info.h index 653107c7c0c70e1269f2bdbb68a50f3da89a9e5b..6e5de4b24f0268e0c4c350ffce8cd541b1a91ca6 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/app_task_info.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/app_task_info.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class AppTaskInfo : public Parcelable { public: /** @@ -110,7 +109,6 @@ private: pid_t pid_ = 0; int32_t appRecordId_ = 0; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_APP_TASK_INFO_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/dummy_configuration.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/dummy_configuration.h index aafe7767beee29198808cf7f45fb4ea619904048..1c7db803e2d8448c28a30f75a8ccc3c54ff0ed49 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/dummy_configuration.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/dummy_configuration.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class Configuration : public Parcelable { public: Configuration() = default; @@ -65,7 +64,6 @@ public: private: std::string testInfostr_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_OHOS_CONFIGURATION_H \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/iapp_state_callback.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/iapp_state_callback.h index e9fdfe6d3d82717e88b931bc1c0750e8e14dd117..5abbef37c64120311e51285435d03a7da7f6f0e3 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/iapp_state_callback.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/iapp_state_callback.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class IAppStateCallback : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AppStateCallback"); @@ -49,7 +48,6 @@ public: TRANSACT_ON_ABILITY_REQUEST_DONE, }; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_IAPP_STATE_CALLBACK_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/priority_object.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/priority_object.h index 64e71f35725f78dbe3ef216d842d55c5ebadcb3d..834e236801578bf4ee7e0c7303d3a50924340dc7 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/priority_object.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/priority_object.h @@ -23,9 +23,7 @@ #include "parcel.h" namespace OHOS { - namespace AppExecFwk { - class PriorityObject : public Parcelable { public: PriorityObject() = default; @@ -160,7 +158,6 @@ private: bool visibleStatus_ = false; bool perceptibleStatus_ = false; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/process_info.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/process_info.h index 969772a45f73cb2b7c54ef834fb96381f6c6c5d5..f9247e2be315e286cb0fe553eeef7742048fe707 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/process_info.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/process_info.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class ProcessInfo : public Parcelable { public: ProcessInfo() = default; @@ -77,7 +76,6 @@ private: std::string processName_; pid_t pid_ = 0; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROCESS_INFO_H diff --git a/interfaces/innerkits/appexecfwk_core/include/appmgr/profile.h b/interfaces/innerkits/appexecfwk_core/include/appmgr/profile.h index 6a0e8ca2e1a34e19391d97d01fb9ba95bd83e115..77589fcd9a8202e5e07b89e6691c3871156f1b0f 100644 --- a/interfaces/innerkits/appexecfwk_core/include/appmgr/profile.h +++ b/interfaces/innerkits/appexecfwk_core/include/appmgr/profile.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class Profile : public Parcelable { public: Profile() = default; @@ -65,7 +64,6 @@ public: private: std::string profileName_; // the name of the ability }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_CORE_INCLUDE_APPMGR_PROFILE_H 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/ams_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp index b5b31a6412a877417e80819e69d5761375ccdbd8..5a309cb691b0a62f7d501b8c69c4ea55b5de99c4 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_proxy.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - AmsMgrProxy::AmsMgrProxy(const sptr &impl) : IRemoteProxy(impl) {} @@ -291,6 +290,5 @@ int AmsMgrProxy::CompelVerifyPermission(const std::string &permission, int pid, message = Str16ToStr8(reply.ReadString16()); return reply.ReadInt32(); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp index 921d6096d3552a602bd50228e2eb74bea25875b5..177edf1602d7d65f43f16b0409dcfe90a454ebbc 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/ams_mgr_stub.cpp @@ -28,7 +28,6 @@ namespace OHOS { namespace AppExecFwk { - AmsMgrStub::AmsMgrStub() { memberFuncMap_[static_cast(IAmsMgr::Message::AMS_LOAD_ABILITY)] = &AmsMgrStub::HandleLoadAbility; diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_launch_data.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_launch_data.cpp index 3913757cdcf076dfc6b2d7e6cb0b596bc38f25a8..aee1ff488872a5c48cea047eb4359249ef745e35 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_launch_data.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_launch_data.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - void AppLaunchData::SetApplicationInfo(const ApplicationInfo &info) { applicationInfo_ = info; @@ -89,6 +88,5 @@ AppLaunchData *AppLaunchData::Unmarshalling(Parcel &parcel) } return appLaunchData; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp index 061584e72882e4f8a85a81b59df14bd796c822b1..29d7f1800983a7b431ba8d49b8b619c8f18252dc 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_client.cpp @@ -27,7 +27,6 @@ namespace OHOS { namespace AppExecFwk { - AppMgrClient::AppMgrClient() { SetServiceManager(std::make_unique()); diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp index 38b506602fd0b4243081544f83ce1ef18951f548..b8f25cfc04b91f9d69b5f9d98503fd8f3ecead87 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_proxy.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - AppMgrProxy::AppMgrProxy(const sptr &impl) : IRemoteProxy(impl) {} @@ -317,7 +316,6 @@ void AppMgrProxy::SetAppFreezingTime(int time) return; } APP_LOGD("end"); - } void AppMgrProxy::GetAppFreezingTime(int &time) @@ -339,7 +337,7 @@ void AppMgrProxy::GetAppFreezingTime(int &time) APP_LOGE("get freeze time : %{public}d ", time); } -template +template int AppMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) { int32_t infoSize = reply.ReadInt32(); @@ -354,6 +352,5 @@ int AppMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcel APP_LOGD("get parcelable infos success"); return NO_ERROR; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp index 63aa66f90c5aefe7a995950b159e59a38b1f6f45..962993ebe541bcce6f3a30ee3ace35aa6719f8c2 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_mgr_stub.cpp @@ -28,7 +28,6 @@ namespace OHOS { namespace AppExecFwk { - AppMgrStub::AppMgrStub() { memberFuncMap_[static_cast(IAppMgr::Message::AMS_APP_ATTACH_APPLICATION)] = @@ -184,6 +183,5 @@ int32_t AppMgrStub::HandleGetAppFreezingTime(MessageParcel &data, MessageParcel reply.WriteInt32(time); return NO_ERROR; } - } // namespace AppExecFwk } // namespace OHOS 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..137b244ce97e8d21e9f96b1d7eef94d2467dddb3 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_process_data.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_process_data.cpp @@ -19,11 +19,10 @@ namespace OHOS { 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 +35,8 @@ bool AppProcessData::ReadFromParcel(Parcel &parcel) pid = parcel.ReadInt32(); + uid = parcel.ReadInt32(); + return true; } @@ -49,6 +50,5 @@ AppProcessData *AppProcessData::Unmarshalling(Parcel &parcel) } return appProcessData; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_record_id.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_record_id.cpp index ad465b779b09625bfdaad0e92a639dcbeaf95d73..c1b5ab57051d17d3361a77274f74fad7caa68f80 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_record_id.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_record_id.cpp @@ -18,13 +18,11 @@ #include "app_record_id.h" namespace OHOS { namespace AppExecFwk { - int32_t AppRecordId::Create() { // Make it atomic to avoid multi app creating concurrently. static std::atomic_int id(0); return ++id; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp index 06d8f2ee2b07c6af33047253a44abe40f103a146..79e206c185ece578d477b3ab79a658421fdbe610 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_host.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - AppSchedulerHost::AppSchedulerHost() { memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_FOREGROUND_APPLICATION_TRANSACTION)] = @@ -164,6 +163,5 @@ int32_t AppSchedulerHost::HandleScheduleProcessSecurityExit(MessageParcel &data, ScheduleProcessSecurityExit(); return NO_ERROR; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp index d76de6f1428c360fd60e048c946903abe8f3a706..0fb7eb627566f353b9f315eb69b7a865760a01c7 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_scheduler_proxy.cpp @@ -269,6 +269,5 @@ void AppSchedulerProxy::ScheduleProcessSecurityExit() APP_LOGW("SendRequest is failed, error code: %{public}d", ret); } } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp index 093d421dab65ee62091dfc5b6a68cda3e428fd93..86e7bafb9e00b3156cf34068a3b0540c55a309ef 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_service_manager.cpp @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - sptr AppServiceManager::GetAppMgrService() const { sptr systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); @@ -33,6 +32,5 @@ sptr AppServiceManager::GetAppMgrService() const } return systemAbilityMgr->GetSystemAbility(APP_MGR_SERVICE_ID); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp index e3eed8ebda07622a88d3ea08464916a90c407b27..9d2a8eeb1fa38b347918bec77f5b05ca98b7445d 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - AppStateCallbackProxy::AppStateCallbackProxy(const sptr &impl) : IRemoteProxy(impl) {} @@ -81,6 +80,5 @@ void AppStateCallbackProxy::OnAppStateChanged(const AppProcessData &appProcessDa } APP_LOGD("end"); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_task_info.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_task_info.cpp index 6af120bb401b83260f018dbd646f1bd0b5c9c835..6a81cd2c214cebd27a817659eccaffa4e00d5a44 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/app_task_info.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/app_task_info.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - const std::string &AppTaskInfo::GetName() const { return appName_; @@ -82,6 +81,5 @@ AppTaskInfo *AppTaskInfo::Unmarshalling(Parcel &parcel) } return appTaskInfo; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/dummy_configuration.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/dummy_configuration.cpp index 8950ae62e8e8cfb93d47eb3909148d6679007ce2..6f53059e0e2da1e9763dace89da2512b6fb43fa0 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/dummy_configuration.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/dummy_configuration.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - Configuration::Configuration(const std::string &name) : testInfostr_(name) {} @@ -49,6 +48,5 @@ bool Configuration::Marshalling(Parcel &parcel) const } return true; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/priority_object.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/priority_object.cpp index c5296ab36d431f018d44f809d6aee3f9958edaf6..23298807f98188427dae97f0b8309d17e71e7609 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/priority_object.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/priority_object.cpp @@ -18,9 +18,7 @@ #include "app_log_wrapper.h" namespace OHOS { - namespace AppExecFwk { - pid_t PriorityObject::GetPid() const { return pid_; @@ -141,6 +139,5 @@ PriorityObject *PriorityObject::Unmarshalling(Parcel &parcel) } return priorityObject; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp index e68ee62a48c62fef3b1627e1906f47dc6563a607..e57d51f60f9f0af3754c25b052277185310a9c0e 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/process_info.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - ProcessInfo::ProcessInfo(const std::string &name, const pid_t &pid) : processName_(name), pid_(pid) {} @@ -61,6 +60,5 @@ bool ProcessInfo::Marshalling(Parcel &parcel) const { return (parcel.WriteString16(Str8ToStr16(processName_)) && parcel.WriteInt32(pid_)); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/appmgr/profile.cpp b/interfaces/innerkits/appexecfwk_core/src/appmgr/profile.cpp index 8d6ea3988ef68d9092c73685b2da35cd14b22b82..8025773b660f3fca3ee371847eed5886efa28dbf 100644 --- a/interfaces/innerkits/appexecfwk_core/src/appmgr/profile.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/appmgr/profile.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - Profile::Profile(const std::string &name) : profileName_(name) {} @@ -47,6 +46,5 @@ bool Profile::Marshalling(Parcel &parcel) const { return (parcel.WriteString16(Str8ToStr16(profileName_))); } - } // namespace AppExecFwk } // namespace OHOS 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 ed9d76cc74c50f82c53bfc24dde2de5a8fec9ed5..6cc4585316b2ef5e49137ef159e9587532da4f51 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; @@ -182,18 +185,24 @@ int BundleMgrHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessagePa case static_cast(IBundleMgr::Message::UNREGISTER_PERMISSIONS_CHANGED): errCode = HandleUnregisterPermissionsChanged(data, reply); break; - case static_cast(IBundleMgr::Message::GET_ALL_FORMS_INFO): + case static_cast(IBundleMgr::Message::GET_ALL_FORMS_INFO): errCode = HandleGetAllFormsInfo(data, reply); - break; - case static_cast(IBundleMgr::Message::GET_FORMS_INFO_BY_APP): + break; + case static_cast(IBundleMgr::Message::GET_FORMS_INFO_BY_APP): errCode = HandleGetFormsInfoByApp(data, reply); - break; - case static_cast(IBundleMgr::Message::GET_FORMS_INFO_BY_MODULE): + break; + case static_cast(IBundleMgr::Message::GET_FORMS_INFO_BY_MODULE): errCode = HandleGetFormsInfoByModule(data, reply); - break; + break; 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); } @@ -201,16 +210,34 @@ int BundleMgrHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessagePa return (errCode == ERR_OK) ? NO_ERROR : UNKNOWN_ERROR; } -int BundleMgrHost::GetUidByBundleName([[maybe_unused]] const std::string &bundleName, const int userId) +int BundleMgrHost::GetUidByBundleName(const std::string &bundleName, const int userId) { - APP_LOGD("need not impl for host interface"); - return Constants::INVALID_UID; + APP_LOGI("begin to get uid of %{public}s", bundleName.c_str()); + BundleInfo bundleInfo; + int uid = Constants::INVALID_UID; + bool ret = GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + if (ret) { + uid = bundleInfo.uid; + APP_LOGD("get bundle uid success"); + } else { + APP_LOGE("can not get bundleInfo's uid"); + } + return uid; } std::string BundleMgrHost::GetAppIdByBundleName([[maybe_unused]] const std::string &bundleName, const int userId) { - APP_LOGD("need not impl for host interface"); - return Constants::EMPTY_STRING; + APP_LOGI("begin to get appId of %{public}s", bundleName.c_str()); + BundleInfo bundleInfo; + std::string appId = Constants::EMPTY_STRING; + bool ret = GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + if (ret) { + appId = bundleInfo.appId; + APP_LOGD("get bundle appId success"); + } else { + APP_LOGE("can not get bundleInfo's appId"); + } + return appId; } std::string BundleMgrHost::GetAppType([[maybe_unused]] const std::string &bundleName) @@ -414,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(); @@ -930,59 +980,59 @@ ErrCode BundleMgrHost::HandleGetBundleInstaller(Parcel &data, Parcel &reply) ErrCode BundleMgrHost::HandleGetAllFormsInfo(Parcel &data, Parcel &reply) { - std::vector infos; - bool ret = GetAllFormsInfo(infos); - if (!reply.WriteBool(ret)) { - APP_LOGE("write failed"); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (ret) { - if (!WriteParcelableVector(infos, reply)) { - APP_LOGE("write failed"); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - } - return ERR_OK; + std::vector infos; + bool ret = GetAllFormsInfo(infos); + if (!reply.WriteBool(ret)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (ret) { + if (!WriteParcelableVector(infos, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return ERR_OK; } ErrCode BundleMgrHost::HandleGetFormsInfoByApp(Parcel &data, Parcel &reply) { - std::string bundlename = data.ReadString(); - std::vector infos; - bool ret = GetFormsInfoByApp(bundlename, infos); - if (!reply.WriteBool(ret)) { - APP_LOGE("write failed"); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (ret) { - if (!WriteParcelableVector(infos, reply)) { - APP_LOGE("write failed"); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - } - return ERR_OK; + std::string bundlename = data.ReadString(); + std::vector infos; + bool ret = GetFormsInfoByApp(bundlename, infos); + if (!reply.WriteBool(ret)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (ret) { + if (!WriteParcelableVector(infos, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return ERR_OK; } ErrCode BundleMgrHost::HandleGetFormsInfoByModule(Parcel &data, Parcel &reply) { - std::string bundlename = data.ReadString(); - std::string modulename = data.ReadString(); - std::vector infos; - bool ret = GetFormsInfoByModule(bundlename, modulename, infos); - if (!reply.WriteBool(ret)) { - APP_LOGE("write failed"); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (ret) { - if (!WriteParcelableVector(infos, reply)) { - APP_LOGE("write failed"); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - } - return ERR_OK; + std::string bundlename = data.ReadString(); + std::string modulename = data.ReadString(); + std::vector infos; + bool ret = GetFormsInfoByModule(bundlename, modulename, infos); + if (!reply.WriteBool(ret)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (ret) { + if (!WriteParcelableVector(infos, reply)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + return ERR_OK; } ErrCode BundleMgrHost::HandleGetShortcutInfos(Parcel &data, Parcel &reply) @@ -1004,6 +1054,43 @@ ErrCode BundleMgrHost::HandleGetShortcutInfos(Parcel &data, Parcel &reply) return ERR_OK; } +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(); + APP_LOGI("bundleName %{public}s, abilityName %{public}s, launchTime %{public}" PRId64, + bundleName.c_str(), + abilityName.c_str(), + launchTime); + + 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) { 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 f259ac27db07c8c757978ff100f9006b337fb50e..0550b9335fb90861aa8347aa0e914e20bbcc0067 100644 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp @@ -161,7 +161,7 @@ int BundleMgrProxy::GetUidByBundleName(const std::string &bundleName, const int std::string BundleMgrProxy::GetAppIdByBundleName(const std::string &bundleName, const int userId) { - APP_LOGI("begin to get uid of %{public}s", bundleName.c_str()); + APP_LOGI("begin to get appId of %{public}s", bundleName.c_str()); BundleInfo bundleInfo; std::string appId = Constants::EMPTY_STRING; bool ret = GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); @@ -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,7 +1307,63 @@ bool BundleMgrProxy::GetShortcutInfos(const std::string &bundleName, std::vector return true; } -template +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) { MessageParcel reply; @@ -1311,7 +1386,7 @@ bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel & return true; } -template +template bool BundleMgrProxy::GetParcelableInfos(IBundleMgr::Message code, MessageParcel &data, std::vector &parcelableInfos) { MessageParcel reply; @@ -1355,4 +1430,4 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file 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..00158f14e39c76d62955ae6ce4ed3b9143cef365 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp @@ -0,0 +1,279 @@ +/* + * 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 = BundleFlag::GET_BUNDLE_DEFAULT; + 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 = BundleFlag::GET_BUNDLE_DEFAULT; + 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/bundlemgr/status_receiver_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/status_receiver_proxy.cpp index 19520010ae46db8cbbdaafa10172e53b7acd1cf3..9c331b168b5aadd371377c0064e4dae1a6ec1fa9 100644 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/status_receiver_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/status_receiver_proxy.cpp @@ -85,7 +85,7 @@ const std::string MSG_ERR_UNINSTALL_KILLING_APP_ERROR = "[ERR_UNINSTALL_KILLING_ const std::string MSG_ERR_UNINSTALL_SYSTEM_APP_ERROR = "[MSG_ERR_UNINSTALL_SYSTEM_APP_ERROR]"; const std::string MSG_ERR_UNKNOWN = "[ERR_UNKNOWN]"; -const std::map MAP_RECEIVED_RESULTS{ +const std::map MAP_RECEIVED_RESULTS { {ERR_OK, {IStatusReceiver::SUCCESS, MSG_SUCCESS}}, {ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR, {IStatusReceiver::ERR_INSTALL_INTERNAL_ERROR, MSG_ERR_INSTALL_INTERNAL_ERROR}}, 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..077a19e82ca0c0a6d5ee6bc8a3d15dbbe702aafb --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp @@ -0,0 +1,132 @@ +/* + * 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_APPEXECFWK_PARCEL_ERROR; + } + 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..edbd2a7173465428992b41132145068ebed63c2c --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp @@ -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. + */ + +#include "appexecfwk_errors.h" +#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_APPEXECFWK_FORM_INVALID_PARAM; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + 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_APPEXECFWK_PARCEL_ERROR; + } + 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_APPEXECFWK_PARCEL_ERROR; +} +} // 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..ea52dc1d756f13e2840e59ccb0368c9f596a5c3d --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp @@ -0,0 +1,599 @@ +/* + * 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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_APPEXECFWK_PARCEL_ERROR; + } + 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_COMMON_CODE; + } + 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 ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + } + 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..42c11f891676683a566f69fb89c235ec015955ff --- /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_APPEXECFWK_FORM_INVALID_PARAM; + } + + 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_PARCEL_ERROR; + } + + 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_PARCEL_ERROR; + } + 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_PARCEL_ERROR; + } + 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_PARCEL_ERROR; + } + 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_PARCEL_ERROR; + } + + 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_PARCEL_ERROR; + } + 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_PARCEL_ERROR; + } + + 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_PARCEL_ERROR; + } + + 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..67b77fff067433432ada5054d586cf6a57ff6e9c --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp @@ -0,0 +1,376 @@ +/* + * 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..5577337a202d69592a35af0edd4a58b5a30d6ebb --- /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 "appexecfwk_errors.h" +#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_APPEXECFWK_FORM_INVALID_PARAM; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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_APPEXECFWK_PARCEL_ERROR; + } + + sptr client = data.ReadParcelable(); + if (client == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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..ced74caec8cb146472a1cb80d43907ffb1c77d4e --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp @@ -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. + */ + +#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..0e6ba42ce5f02d3a57456534e76d3faa869455d0 --- /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_APPEXECFWK_FORM_INVALID_PARAM; + } + + 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_APPEXECFWK_PARCEL_ERROR); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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_APPEXECFWK_PARCEL_ERROR; + 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_APPEXECFWK_PARCEL_ERROR); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + 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..eb433ebd4e68dce02e0bff470c13de67cb007f72 --- /dev/null +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp @@ -0,0 +1,108 @@ + +/* + * 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..cee0890826f015e1247914e34c59aa5f6773395a --- /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 "appexecfwk_errors.h" +#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_APPEXECFWK_PARCEL_ERROR; + } + 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_APPEXECFWK_PARCEL_ERROR; + } + 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..5b10fb34c816c8381aea8274db6d70c356cb0464 --- /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", + ] +} +config("fmskit_public_config") { + include_dirs = [ + "$SUBSYSTEM_DIR/common/log/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/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 = [ ":fmskit_public_config" ] + sources = [ + "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_errors.cpp", + "$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", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_L2:samgr_proxy", + ] + + 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_errors.h b/interfaces/innerkits/fmskit/native/include/form_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..1510f4670de36c19256f83fd8ffe2926ffd5cfbe --- /dev/null +++ b/interfaces/innerkits/fmskit/native/include/form_errors.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_OHOS_FORM_ERRORS_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H + +#include +#include + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormErrors + * FormErrors is used to access form error message. + */ +class FormErrors final : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(FormErrors) +public: + DISALLOW_COPY_AND_MOVE(FormErrors); + + /** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ + std::string GetErrorMessage(int errCode); + +private: + /** + * @brief Init error message map object. + * + */ + void InitErrorMessageMap(); + +private: + std::map errorMessageMap_; + + +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H \ No newline at end of file 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..ec455552e483cf19ee8f2772804020bc57c676fb --- /dev/null +++ b/interfaces/innerkits/fmskit/native/include/form_mgr.h @@ -0,0 +1,261 @@ +/* + * 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. + */ + 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); + + /** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ + std::string GetErrorMessage(int errCode); +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_errors.cpp b/interfaces/innerkits/fmskit/native/src/form_errors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25861a6a41d297157709e5f3789d18d56a0f3114 --- /dev/null +++ b/interfaces/innerkits/fmskit/native/src/form_errors.cpp @@ -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. + */ + +#include "appexecfwk_errors.h" +#include "form_errors.h" + +namespace OHOS { +namespace AppExecFwk { +FormErrors::FormErrors() +{ + InitErrorMessageMap(); +} +FormErrors::~FormErrors() +{ +} + +/** + * @brief Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ +std::string FormErrors::GetErrorMessage(int errCode) +{ + if(errorMessageMap_.find(errCode) != errorMessageMap_.end()) { + return errorMessageMap_[errCode]; + } + else { + return errorMessageMap_[ERR_APPEXECFWK_FORM_COMMON_CODE]; + } +} + +/** + * @brief Init error message map object. + * + */ +void FormErrors::InitErrorMessageMap() +{ + errorMessageMap_ = { // error + message + { + ERR_APPEXECFWK_FORM_COMMON_CODE, "some internal server error occurs.", + }, + { + ERR_APPEXECFWK_FORM_PERMISSION_DENY, + "check permission deny, need to request ohos.permission.REQUIRE_FORM.", + }, + { + ERR_APPEXECFWK_FORM_GET_INFO_FAILED, "can't get form info by the formName.", + }, + { + ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, "the requested bundle name does not exist.", + }, + { + ERR_APPEXECFWK_FORM_INVALID_PARAM, "invalid params received on operating form.", + }, + { + ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, "the form id and form config are not matched.", + }, + { + ERR_APPEXECFWK_FORM_NOT_EXIST_ID, "the requested form id is not existed on fms.", + }, + { + ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, "fms bind provider failed.", + }, + { + ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, "exceed max forms in system, current limit is 512.", + }, + { + ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, "exceed max instances per form, limit is 32.", + }, + { + ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, + "the form to be operated is not self-owned or has been deleted already.", + }, + { + ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, "fms notify provider to delete failed.", + }, + { + ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, "exceed max forms per client, limit is 256.", + }, + { + ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, "exceed max temp forms in system, limit is 256.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_MODULE, "the module not exist in the bundle.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, "the ability not exist in the module.", + }, + { + ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION, "the dimension not exist in the form.", + }, + { + ERR_APPEXECFWK_FORM_FA_NOT_INSTALLED, "the ability not installed,need install first.", + }, + { + ERR_APPEXECFWK_FORM_MAX_REQUEST, "too many request,try again later.", + }, + { + ERR_APPEXECFWK_FORM_MAX_REFRESH, "already refresh 50 times.", + }, + { + ERR_APPEXECFWK_FORM_GET_BMS_FAILED, "get bms rpc failed.", + }, + { + ERR_APPEXECFWK_FORM_GET_FMS_FAILED, "get fms rpc failed.", + }, + { + ERR_APPEXECFWK_FORM_SEND_FMS_MSG, "send request to fms failed.", + }, + { + ERR_APPEXECFWK_FORM_FORM_DUPLICATE_ADDED, "form do not support acquire same id twice.", + }, + { + ERR_APPEXECFWK_FORM_IN_RECOVER, "form is in recover status, can't do action on form.", + }, + { + ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED, "get system manager failed.", + }, + { + ERR_APPEXECFWK_PARCEL_ERROR, "read parcelable info failed.", + }, + }; +} + +} // namespace AppExecFwk +} // namespace OHOS \ 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..f3a48d6e760e8b293723ddb2df18913c5def0891 --- /dev/null +++ b/interfaces/innerkits/fmskit/native/src/form_host_client.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 + +#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}" PRId64 ".", __func__, formId); + return; + } + APP_LOGI("%{public}s, formId: %{public}" PRId64 ", jspath: %{public}s, data: %{public}s", __func__, formId, + formJsInfo.jsFormCodePath.c_str(), 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}" PRId64 ".", __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}" PRId64 ".", __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..b728408bb40fcda1279f829295e011411675cc1c --- /dev/null +++ b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp @@ -0,0 +1,507 @@ +/* + * 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_errors.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 Get the error message content. + * + * @param errCode Error code. + * @return Message content. + */ +std::string FormMgr::GetErrorMessage(int errCode) +{ + return FormErrors::GetInstance().GetErrorMessage(errCode); +} + +/** + * @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_APPEXECFWK_FORM_COMMON_CODE; + } + if ((remoteObject->IsProxyObject()) && (!remoteObject->AddDeathRecipient(deathRecipient_))) { + APP_LOGE("%{public}s :Add death recipient to FormMgrService failed.", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + 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/libeventhandler/include/event_handler.h b/interfaces/innerkits/libeventhandler/include/event_handler.h index 013c5067ef5716d697a215ac1e5d9a2f20cf2397..d232a1a195082090f420507ca7dfe0c7000a4aa6 100644 --- a/interfaces/innerkits/libeventhandler/include/event_handler.h +++ b/interfaces/innerkits/libeventhandler/include/event_handler.h @@ -27,7 +27,7 @@ enum class EventType { TIMING_EVENT = 2, }; -template +template class ThreadLocalData; class EventHandler : public std::enable_shared_from_this { @@ -154,7 +154,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, const std::shared_ptr &object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -168,7 +168,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, const std::weak_ptr &object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -182,7 +182,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, std::unique_ptr &object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -196,7 +196,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendEvent(uint32_t innerEventId, std::unique_ptr &&object, int64_t delayTime = 0) { return SendEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -243,7 +243,7 @@ public: * @param object Shared pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, const std::shared_ptr &object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -256,7 +256,7 @@ public: * @param object Weak pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, const std::weak_ptr &object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -269,7 +269,7 @@ public: * @param object Unique pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, std::unique_ptr &object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -282,7 +282,7 @@ public: * @param object Unique pointer of object. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendImmediateEvent(uint32_t innerEventId, std::unique_ptr &&object) { return SendImmediateEvent(InnerEvent::Get(innerEventId, object)); @@ -333,7 +333,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, const std::shared_ptr &object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -347,7 +347,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, const std::weak_ptr &object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -361,7 +361,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, std::unique_ptr &object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -375,7 +375,7 @@ public: * @param delayTime Process the event after 'delayTime' milliseconds. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendHighPriorityEvent(uint32_t innerEventId, std::unique_ptr &&object, int64_t delayTime = 0) { return SendHighPriorityEvent(InnerEvent::Get(innerEventId, object), delayTime); @@ -539,7 +539,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent( uint32_t innerEventId, const std::shared_ptr &object, Priority priority = Priority::LOW) { @@ -554,7 +554,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent(uint32_t innerEventId, const std::weak_ptr &object, Priority priority = Priority::LOW) { return SendSyncEvent(InnerEvent::Get(innerEventId, object), priority); @@ -568,7 +568,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent(uint32_t innerEventId, std::unique_ptr &object, Priority priority = Priority::LOW) { return SendSyncEvent(InnerEvent::Get(innerEventId, object), priority); @@ -582,7 +582,7 @@ public: * @param priority Priority of the event queue for this event, IDLE is not permitted for sync event. * @return Returns true if event has been sent successfully. */ - template + template inline bool SendSyncEvent(uint32_t innerEventId, std::unique_ptr &&object, Priority priority = Priority::LOW) { return SendSyncEvent(InnerEvent::Get(innerEventId, object), priority); @@ -686,7 +686,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, const std::shared_ptr &object, int64_t taskTime, Priority priority = Priority::LOW) { @@ -702,7 +702,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, const std::weak_ptr &object, int64_t taskTime, Priority priority = Priority::LOW) { @@ -718,7 +718,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, std::unique_ptr &object, int64_t taskTime, Priority priority = Priority::LOW) { @@ -734,7 +734,7 @@ public: * @param priority Priority of the event queue for this event * @return Returns true if event has been sent successfully. */ - template + template inline bool SendTimingEvent( uint32_t innerEventId, std::unique_ptr &&object, int64_t taskTime, Priority priority = Priority::LOW) { diff --git a/interfaces/innerkits/libeventhandler/include/inner_event.h b/interfaces/innerkits/libeventhandler/include/inner_event.h index ca13bf30a7e703c46aed1163871819f8326e3ad8..0cd2e3f1aea2d3b2617c5ec31060fa9465bcaa8b 100644 --- a/interfaces/innerkits/libeventhandler/include/inner_event.h +++ b/interfaces/innerkits/libeventhandler/include/inner_event.h @@ -67,7 +67,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, const std::shared_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -83,7 +83,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, const std::weak_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -99,7 +99,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, std::unique_ptr &&object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -115,7 +115,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, std::unique_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -131,7 +131,7 @@ public: * @param object Shared pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, const std::shared_ptr &object) { auto event = Get(innerEventId, param); @@ -147,7 +147,7 @@ public: * @param object Weak pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, const std::weak_ptr &object) { auto event = Get(innerEventId, param); @@ -163,7 +163,7 @@ public: * @param object Unique pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, std::unique_ptr &&object) { auto event = Get(innerEventId, param); @@ -179,7 +179,7 @@ public: * @param object Unique pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, std::unique_ptr &object) { auto event = Get(innerEventId, param); @@ -290,7 +290,7 @@ public: * * @return Returns shared pointer of saved object. */ - template + template std::shared_ptr GetSharedObject() const { const std::shared_ptr &sharedObject = *reinterpret_cast *>(smartPtr_); @@ -312,7 +312,7 @@ public: * * @return Returns unique pointer of saved object. */ - template + template std::unique_ptr GetUniqueObject() const { std::unique_ptr &object = *reinterpret_cast *>(smartPtr_); @@ -329,7 +329,7 @@ public: * * @return Returns unique pointer of saved object. */ - template + template std::unique_ptr GetUniqueObject() const { std::unique_ptr &object = *reinterpret_cast *>(smartPtr_); @@ -401,7 +401,7 @@ private: static void WarnSmartPtrCastMismatch(); - template + template static void ReleaseSmartPtr(void *smartPtr) { if (smartPtr != nullptr) { @@ -409,7 +409,7 @@ private: } } - template + template inline void SaveSharedPtr(const T &object) { smartPtr_ = new T(object); @@ -417,7 +417,7 @@ private: smartPtrTypeId_ = CalculateSmartPtrTypeId(object); } - template + template inline void SaveUniquePtr(T &object) { smartPtr_ = new T(std::move(object)); @@ -430,7 +430,7 @@ private: */ #ifdef __GXX_RTTI // If RTTI(Run-Time Type Info) is enabled, use hash code of type info. - template + template static inline size_t CalculateSmartPtrTypeId(const T &) { return typeid(T).hash_code(); @@ -442,25 +442,25 @@ private: static const size_t UNIQUE_PTR_TYPE = 0x30000000; static const size_t UNIQUE_PTR_ARRAY_TYPE = 0x40000000; - template + template static inline size_t CalculateSmartPtrTypeId(const std::shared_ptr &) { return (sizeof(T) | SHARED_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::weak_ptr &) { return (sizeof(T) | WEAK_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::unique_ptr &) { return (sizeof(T) | (sizeof(D) - 1) | UNIQUE_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::unique_ptr &) { return (sizeof(T) | (sizeof(D) - 1) | UNIQUE_PTR_ARRAY_TYPE); diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h index 106b6619b9654307381ed05ca1fcb3b97d27c248..96326fb7fd18ef0d41168f8c3cec626a7283069b 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h @@ -28,7 +28,7 @@ namespace OHOS { namespace AppExecFwk { /** - *Base implementation for interface of TaskDispatcher. + * Base implementation for interface of TaskDispatcher. */ class BaseTaskDispatcher : public TaskDispatcher { 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/group_impl.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/group_impl.h index a7bc92c1f7dd4a4c1e7d5c7f459eb8fd50920b73..13fc253b6b575de91f9ea5ddf18a9d22b62caae7 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/group_impl.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/group_impl.h @@ -30,6 +30,7 @@ class GroupImpl : public Group { public: GroupImpl(); + ~GroupImpl() = default; /** * Wait all tasks associated to this group to be done. * @param timeout is the max waiting time for jobs in group execute, in ms. 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..af3847c8caf7c64d45ccae9f15ff976ef4a45870 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h @@ -33,55 +33,9 @@ namespace AppExecFwk { /** * Dispatcher for serial thread model. - * - * */ class SerialTaskDispatcher : public BaseTaskDispatcher, public std::enable_shared_from_this { -private: - static std::string DISPATCHER_TAG; - static std::string ASYNC_DISPATCHER_TAG; - static std::string SYNC_DISPATCHER_TAG; - static std::string DELAY_DISPATCHER_TAG; - - std::atomic running_; - ConcurrentQueue> workingTasks_; - - std::shared_ptr executor_; - std::mutex mutex_; - -private: - ErrCode OnNewTaskIn(std::shared_ptr &task); - - ErrCode Prepare(std::shared_ptr &task); - - /** - * Callback for task when finish. - * - */ - void OnTaskDone(); - - bool Schedule(); - - /** - * Do task in turn, until the task queue is empty. - * - * @param isExhausted is an inaccurate judge indicate that the workingTasks is empty. If true, do double-check. - * @return true if has work remain to do else false. - * - */ - bool DoNext(bool isExhausted); - - void DoWork(std::shared_ptr &task); - public: - /** - * Constructs a serial TaskDispatcher using priority. - * - * @param dispatcherName is the identity for dispatcher. It's for debug purpose. - * @param priority is the priority for tasks dispatched by this Dispatcher. - * @param executor contains thread pool(s) for executing tasks concurrently. - * - */ SerialTaskDispatcher( const std::string &dispatcherName, const TaskPriority priority, const std::shared_ptr &executor); ~SerialTaskDispatcher(){}; @@ -123,12 +77,46 @@ 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. * */ std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs); +private: + ErrCode OnNewTaskIn(std::shared_ptr &task); + + ErrCode Prepare(std::shared_ptr &task); + + /** + * Callback for task when finish. + * + */ + void OnTaskDone(); + + bool Schedule(); + + /** + * Do task in turn, until the task queue is empty. + * + * @param isExhausted is an inaccurate judge indicate that the workingTasks is empty. If true, do double-check. + * @return true if has work remain to do else false. + * + */ + bool DoNext(bool isExhausted); + + void DoWork(std::shared_ptr &task); +private: + static std::string DISPATCHER_TAG; + static std::string ASYNC_DISPATCHER_TAG; + static std::string SYNC_DISPATCHER_TAG; + static std::string DELAY_DISPATCHER_TAG; + + std::atomic running_; + ConcurrentQueue> workingTasks_; + + std::shared_ptr executor_; + std::mutex mutex_; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_dispatcher_config.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_dispatcher_config.h index c03454ef526aafcf8b0c83fc57be2e27d900fe45..9b84879200b133577da50416cf5b42cd10145828 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_dispatcher_config.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/spec_dispatcher_config.h @@ -31,6 +31,7 @@ public: name_ = name; priority_ = priority; } + ~SpecDispatcherConfig(){}; std::string GetName() { return name_; 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..0df6dd7fc28f510e11a25fcae605c28dc410188e 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/barrier_handler.h +++ b/interfaces/innerkits/task_dispatcher/include/task/barrier_handler.h @@ -29,7 +29,7 @@ namespace AppExecFwk { class BarrierHandler : public TaskExecuteInterceptor { public: BarrierHandler(const std::shared_ptr &executor); - + ~BarrierHandler() = default; /** * Intercept executing a task. */ @@ -58,6 +58,7 @@ private: tasks_ = tasks; barrier_ = barrier; }; + ~BarrierPair() = default; }; class MyTaskListener : public TaskListener { @@ -68,7 +69,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..160874014f2926e8d949f9507634122dd0d6e288 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 - */ + ~SyncTask() = default; 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..4d58c0e9b44d70e53b7ac99a3d429d86a0d111cc 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task.h @@ -31,94 +31,64 @@ 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); virtual ~Task(); /** - *@brief invoke the function to execute the task - *@param - - *@return void + * @brief invoke the function to execute the task */ virtual void Run(); /** - * @brief Gets the priority. - * @param - - * @return The priority. + * @brief Gets the priority. + * @return The priority. */ TaskPriority GetPriority() const; /** - * @brief Sets the sequence. - * @param - - * @param sequence The sequence - * @return void + * @brief Sets the sequence. + * @param sequence The sequence */ void SetSequence(long sequence); /** - *@brief Gets the sequence. - *@param - - *@return The sequence. + * @brief Gets the sequence. + * @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. + * @brief Revoke this task if hasn't run. + * @return true if set revoked or already revoked. False if the task has start executing. */ bool Revoke() override; /** - *@brief Adds a task listener. - *@param listener The listener - *@return void + * @brief Adds a task listener. + * @param listener The listener */ void AddTaskListener(const std::shared_ptr &listener); /** - *@brief Called when task is about to run. - *@param - - *@return void + * @brief Called when task is about to run. */ void BeforeTaskExecute(); /** - *@brief Called when task is done. - *@param - - *@return void + * @brief Called when task is done. */ void AfterTaskExecute(); /** - *@brief Called when task is canceled. - *@param - - *@return void + * @brief Called when task is canceled. */ 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: @@ -132,9 +102,9 @@ private: }; /** - *@brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. - *@param - - *@return bool + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param - + * @return bool */ bool EnterExecute(); @@ -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_listener.h b/interfaces/innerkits/task_dispatcher/include/task/task_listener.h index 4ba73a96b61cce7f19bde0abb6a1643ac5a76e9e..27ff313fffcb70f78e1c3c1b611d083047ab96c9 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task_listener.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task_listener.h @@ -27,9 +27,9 @@ class TaskListener { public: virtual ~TaskListener(){}; /** - *@brief Called when task stage changed. - *@param stage The stage - *@return void + * @brief Called when task stage changed. + * @param stage The stage + * @return void */ virtual void OnChanged(const TaskStage &stage) = 0; }; diff --git a/interfaces/innerkits/task_dispatcher/include/task/task_stage.h b/interfaces/innerkits/task_dispatcher/include/task/task_stage.h index 00678029d0d49e79432782d4048a2cb00c631d6a..0549e7c751f07eeee520651b983cd32e6f626fe3 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,12 @@ public: { index_ = index; } - + ~TaskStage() = default; + /** + * 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..6126745ee0422a347a8c931192e8f8c491e182fc 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h @@ -24,11 +24,11 @@ namespace OHOS { namespace AppExecFwk { -template +template class ConcurrentQueue { public: - ConcurrentQueue() : empty_() - {} + ConcurrentQueue() : empty_(){}; + ~ConcurrentQueue() = default; /** * get data without block @@ -52,7 +52,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 +64,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..eee772130055a408da163b6e7be15d4d3cb2e53f 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 GetStateFromControl(unsigned 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..578b4132722c19191bb91312bb3cf5cb58fa678c 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..2ca74d97b58bb6ac52c7b3d098004113916fee3e 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,22 +118,24 @@ 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); - std::function callback = - std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask); + std::function callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask); bool executeFlag = executor_->DelayExecute(callback, delayMs); if (!executeFlag) { 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 +171,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..e2c737e8914e4a08b270f61ef3dd1d1043c8a568 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; } @@ -115,6 +128,8 @@ int TaskDispatcherContext::MapPriorityIndex(TaskPriority priority) const return DEFAULT_PRIORITY_INDEX; case TaskPriority::LOW: return LOW_PRIORITY_INDEX; + default: + return DEFAULT_PRIORITY_INDEX; } APP_LOGE("TaskDispatcherContext.mapPriorityIndex unhandled priority=%{public}d", priority); @@ -123,32 +138,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..0f4706ac1abbd1a1cee09166eeed1ce0ceb86957 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); } @@ -159,9 +171,9 @@ bool BarrierHandler::HasTask(const std::set> &tasks) std::set> BarrierHandler::CreateTaskSet(std::shared_ptr &firstTask) { - std::set> newSet; - newSet.insert(firstTask); - return newSet; + std::set> taskSet; + taskSet.insert(firstTask); + return taskSet; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp b/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp index ebe4759e836b5006be91f4c07fcb9bfd94ab67b7..211b8250848b4f93dabccc4d8f0d668c0c0c68ff 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/sync_task.cpp @@ -20,7 +20,7 @@ namespace OHOS { namespace AppExecFwk { // Help to calculate hash code of object. -template +template inline size_t CalculateHashCode(const T &obj) { std::hash calculateHashCode; @@ -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..6f73cfc53f54db4add6838e27b3120808629a72c 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/task.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/task.cpp @@ -30,36 +30,36 @@ 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() {} /** - *@brief invoke the function to execute the task - *@param None - *@return None + * @brief invoke the function to execute the task + * @param None + * @return None */ 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"); } /** - * @brief Gets the priority. - * @param None - * @return The priority. + * @brief Gets the priority. + * @param None + * @return The priority. */ TaskPriority Task::GetPriority() const { @@ -67,10 +67,10 @@ TaskPriority Task::GetPriority() const } /** - * @brief Sets the sequence. - * @param None - * @param sequence The sequence - * @return None + * @brief Sets the sequence. + * @param None + * @param sequence The sequence + * @return None */ void Task::SetSequence(long sequence) { @@ -78,9 +78,9 @@ void Task::SetSequence(long sequence) } /** - *@brief Gets the sequence. - *@param None - *@return The sequence. + * @brief Gets the sequence. + * @param None + * @return The sequence. */ long Task::GetSequence() const { @@ -88,18 +88,18 @@ long Task::GetSequence() const } /** - *@brief Revoke this task if hasn't run. - *@param None - *@return true if set revoked or already revoked. False if the task has start executing. + * @brief Revoke this task if hasn't run. + * @param None + * @return true if set revoked or already revoked. False if the task has start executing. */ 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(); } @@ -107,20 +107,20 @@ bool Task::Revoke() } /** - *@brief Adds a task listener. - *@param listener The listener - *@return None + * @brief Adds a task listener. + * @param listener The listener + * @return None */ 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); } /** - *@brief Called when task is about to run. - *@param None - *@return None + * @brief Called when task is about to run. + * @param None + * @return None */ void Task::BeforeTaskExecute() { @@ -130,47 +130,47 @@ void Task::BeforeTaskExecute() } /** - *@brief Called when task is done. - *@param None - *@return None + * @brief Called when task is done. + * @param None + * @return None */ 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); } } /** - *@brief Called when task is canceled. - *@param None - *@return None + * @brief Called when task is canceled. + * @param None + * @return None */ void Task::OnTaskCanceled() { - APP_LOGD("Task.OnTaskCanceled taskStage called REVOKED"); + APP_LOGI("Task.OnTaskCanceled taskStage called REVOKED"); ConcurrentQueueStatusUpdate(TaskStage::REVOKED); } /** - *@brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. - *@param None - *@return bool + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param None + * @return bool */ 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..069a8dcdb6de741a9d27775afff1a0705ec2010f 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) @@ -94,35 +94,35 @@ std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr std::shared_ptr nullRunnable = nullptr; std::shared_ptr next = nullptr; - for (;;) { + 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"); } } } @@ -204,18 +204,18 @@ bool TaskExecutor::EnsureConsumeStarted() void TaskExecutor::Consume() { - for (;;) { + 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..1505b10dcb3437ac7b5e13f2a1184653cfb09ccd 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); @@ -237,17 +239,17 @@ bool WorkerPool::AddWorker(const std::shared_ptr &delegate, const std: std::unique_lock mLock(poolLock_); std::shared_ptr newThread = nullptr; - for (;;) { - int value = control_.load(); + for(;;){ + 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; } @@ -319,45 +319,45 @@ bool WorkerPool::IsRunning(int ctl) return ctl < CLOSING; } -int WorkerPool::GetStateFromControl(int ctl) +int WorkerPool::GetStateFromControl(unsigned int ctl) { return ctl & ~CAPACITY; } -void WorkerPool::AdvanceStateTo(int target) +void WorkerPool::AdvanceStateTo(unsigned int target) { - APP_LOGD("WorkerPool::AdvanceStateTo begin"); - for (;;) { - int current = control_.load(); + APP_LOGI("WorkerPool::AdvanceStateTo begin"); + for(;;){ + 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; } bool WorkerPool::CompareAndIncThreadNum(int expect) { - int ctl = control_.load(); + unsigned int ctl = control_.load(); int state = GetStateFromControl(ctl); return CompareAndSet(control_, ctl, CombineToControl(state, expect + 1)); } 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) @@ -367,7 +367,7 @@ bool WorkerPool::CompareAndDecThreadNum(int expect) bool WorkerPool::CompareAndDecNum(int expectCount) { - int curr = control_.load(); + unsigned int curr = control_.load(); int state = GetStateFromControl(curr); int expectControl = CombineToControl(state, expectCount); return CompareAndDecThreadNum(expectControl); diff --git a/interfaces/innerkits/task_dispatcher/test/BUILD.gn b/interfaces/innerkits/task_dispatcher/test/BUILD.gn index 594612124112884601ec73953df3db6f8b59dd2f..5e4dd762e6ca0416434fd730f9ea5525bc29155e 100644 --- a/interfaces/innerkits/task_dispatcher/test/BUILD.gn +++ b/interfaces/innerkits/task_dispatcher/test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# 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 diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp index 90a170230aeecf83d69f2370c060a6d3f5f18aeb..57eedb0cf9657977627c8e13fc5f1893f1f6e89a 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp @@ -76,7 +76,6 @@ HWTEST(BarrierHandlerTest, BarrierHandler_interceptTest_001, TestSize.Level0) auto name = std::string("BarrierHandler_interceptTest_001"); GTEST_LOG_(INFO) << name << " start"; std::shared_ptr barrierHandler = CreateBarrierHandler(); - //每次添加组任务, 给任务添加监听,当任务完成时候。。。。。判断任务是否应该执行(前面有屏障时候,不立即执行)。 std::shared_ptr runnable = std::make_shared([&]() { GTEST_LOG_(INFO) << name << " Runnable"; }); std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, nullptr); ErrCode result = barrierHandler->Intercept(task); 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/groupImpl_test/groupImpl_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp index 0daf94b2784c4f5bb94ac7cb21f7097c15266113..2a9931d164d40993ff0c34db86bde717061e9bdc 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp @@ -175,9 +175,9 @@ HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_002, TestSize.Level0) std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); groupPtr->AddNotification(notification); } - std::shared_ptr newNotification = + std::shared_ptr notificationTask = std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); - bool result = groupPtr->AddNotification(newNotification); + bool result = groupPtr->AddNotification(notificationTask); EXPECT_TRUE(result); GTEST_LOG_(INFO) << name << " end"; } @@ -198,9 +198,9 @@ HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_003, TestSize.Level0) std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); groupPtr->AddNotification(notification); } - std::shared_ptr newNotification = + std::shared_ptr notificationTask = std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); - bool result = groupPtr->AddNotification(newNotification); + bool result = groupPtr->AddNotification(notificationTask); EXPECT_FALSE(result); GTEST_LOG_(INFO) << name << " 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..a7e924cf0234769f389676492b8b6b03d87e4b14 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"; } @@ -194,7 +194,6 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDisp CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); std::atomic count(0); EXPECT_EQ(count.load(), 0); - //添加个group1 std::shared_ptr group1 = parallelTaskDispatcherBase->CreateDispatchGroup(); std::shared_ptr group1Run1 = std::make_shared([&]() { std::this_thread::sleep_for(std::chrono::milliseconds(800)); @@ -209,7 +208,6 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDisp GTEST_LOG_(INFO) << name << " Group1 : Runnable2"; }); parallelTaskDispatcherBase->AsyncGroupDispatch(group1, group1Run2); - //添加group2 std::shared_ptr group2 = parallelTaskDispatcherBase->CreateDispatchGroup(); std::shared_ptr group2Run = std::make_shared([&]() { count.fetch_add(1); @@ -235,6 +233,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..07212360d09691672937333f42bf650d061381d0 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 @@ -59,17 +59,10 @@ void SpecTaskDispatcherTest::SetUp() void SpecTaskDispatcherTest::TearDown() {} -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(": "); } std::shared_ptr CreateSpecTaskDispatcher() @@ -94,7 +87,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 +107,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 +175,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 +216,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 +276,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 +312,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..b86f8b04693b658a729b98acb28c86a3a5bb83a3 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 @@ -55,7 +55,6 @@ void GlobalTaskDispatcherModuleTest::TearDown() std::shared_ptr GlobalTaskDispatcherModuleTest::GetMtGlobalTaskDispatcher(TaskPriority priority) const { - // TaskDispatcherContext context; std::shared_ptr ptrGlobalTaskDispatcher = context->GetGlobalTaskDispatcher(priority); return ptrGlobalTaskDispatcher; } @@ -68,7 +67,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..ee540863f7bea3473a55fb9d1ed25d8b7618f0dd 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 += 10; } 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/appMgr/app_mgr.cpp b/kits/appkit/napi/appMgr/app_mgr.cpp index c0a84af847fe690378445eed29eb5952abe745be..bedc57148c7ea64696e4d9c8b31f51b77b4697f4 100755 --- a/kits/appkit/napi/appMgr/app_mgr.cpp +++ b/kits/appkit/napi/appMgr/app_mgr.cpp @@ -39,7 +39,7 @@ static napi_value ParseBundleName(napi_env env, std::string &bundleName, napi_va size_t len = 0; napi_get_value_string_utf8(env, args, buf, BUFFER_LENGTH_MAX, &len); HILOG_INFO("bundleName= [%{public}s].", buf); - bundleName = std::string{buf}; + bundleName = std::string {buf}; // create result code napi_value result; status = napi_create_int32(env, 1, &result); @@ -67,14 +67,15 @@ napi_value NAPI_KillProcessesByBundleName(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); - if (argc >= 2) { + size_t argcNum = 2; + if (argc >= argcNum) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); } AsyncCallbackInfo *async_callback_info = - new AsyncCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + new AsyncCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr }; std::string bundleName; ParseBundleName(env, bundleName, argv[0]); diff --git a/kits/appkit/napi/appMgr/native_module.cpp b/kits/appkit/napi/appMgr/native_module.cpp index 0e4c22c52e39b93a785a74ead4c43167afa75fc5..f1e4c8ae9fb3efb64c5129d222e659fc7429427c 100644 --- a/kits/appkit/napi/appMgr/native_module.cpp +++ b/kits/appkit/napi/appMgr/native_module.cpp @@ -33,7 +33,8 @@ static napi_value Init(napi_env env, napi_value exports) * Propertise define */ napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("killProcessesByBundleName", NAPI_KillProcessesByBundleName)}; + DECLARE_NAPI_FUNCTION("killProcessesByBundleName", NAPI_KillProcessesByBundleName), + }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); HILOG_INFO("native_module Init end..."); @@ -44,13 +45,15 @@ EXTERN_C_END /* * Module define */ -static napi_module _module = {.nm_version = 1, +static napi_module _module = { + .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = "napi_app_mgr", .nm_priv = ((void *)0), - .reserved = {0}}; + .reserved = {0}, + }; /* * Module register function */ 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 6e039fb62a3ca9f7d120ce5ca7c033b76d178a89..4245612309d38edabb9dde4775d30277c7db880b 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,6 +39,12 @@ 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 { @@ -56,6 +65,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; @@ -69,6 +96,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; @@ -113,9 +149,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)); @@ -181,14 +220,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; @@ -204,7 +244,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; @@ -217,7 +258,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; @@ -273,6 +313,15 @@ 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)); @@ -296,7 +345,8 @@ static void ConvertAbilityInfo(napi_env env, napi_value objAbilityInfo, const Ab env, abilityInfo.deviceCapabilities[idx].c_str(), NAPI_AUTO_LENGTH, &nDeviceCapability)); NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nDeviceCapabilities, idx, nDeviceCapability)); } - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "deviceCapabilities", nDeviceCapabilities)); + NAPI_CALL_RETURN_VOID( + env, napi_set_named_property(env, objAbilityInfo, "deviceCapabilities", nDeviceCapabilities)); napi_value nDeviceTypes; NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nDeviceTypes)); @@ -365,15 +415,9 @@ static void ConvertAbilityInfo(napi_env env, napi_value objAbilityInfo, const Ab NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, DEFAULT_INT32, &nLabelId)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "labelId", nLabelId)); - napi_value nFormEntities; - NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nFormEntities)); - for (size_t idx = 0; idx < abilityInfo.formEntity.size(); idx++) { - napi_value nFormEntity; - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, abilityInfo.formEntity[idx].c_str(), NAPI_AUTO_LENGTH, &nFormEntity)); - NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nFormEntities, idx, nFormEntity)); - } - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "formEntity", nFormEntities)); + napi_value nFormEntity; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, abilityInfo.formEntity, &nFormEntity)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "formEntity", nFormEntity)); napi_value nMinFormHeight; NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, abilityInfo.minFormHeight, &nMinFormHeight)); @@ -396,7 +440,8 @@ static void ConvertAbilityInfo(napi_env env, napi_value objAbilityInfo, const Ab NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "subType", nSubType)); napi_value nReadPermission; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, std::string().c_str(), NAPI_AUTO_LENGTH, &nReadPermission)); + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, std::string().c_str(), NAPI_AUTO_LENGTH, &nReadPermission)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "readPermission", nReadPermission)); napi_value nWritePermission; @@ -419,6 +464,128 @@ static void ConvertAbilityInfo(napi_env env, napi_value objAbilityInfo, const Ab NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objAbilityInfo, "metaData", nMetaData)); } +static void ProcessAbilityInfos( + napi_env env, napi_value result, const std::vector abilityInfos) +{ + if (abilityInfos.size() > 0) { + HILOG_INFO("-----abilityInfos is not null-----"); + size_t index = 0; + for (const auto &item : abilityInfos) { + HILOG_INFO("name{%s} ", item.name.c_str()); + napi_value objAbilityInfo = nullptr; + napi_create_object(env, &objAbilityInfo); + ConvertAbilityInfo(env, objAbilityInfo, item); + napi_set_element(env, result, index, objAbilityInfo); + index++; + } + } else { + HILOG_INFO("-----abilityInfos is null-----"); + } +} + +static void ConvertHapModuleInfo(napi_env env, napi_value objHapModuleInfo, const HapModuleInfo &hapModuleInfo) +{ + napi_value nName; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, hapModuleInfo.name.c_str(), NAPI_AUTO_LENGTH, &nName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "name", nName)); + HILOG_INFO("ConvertHapModuleInfo name=%{public}s.", hapModuleInfo.name.c_str()); + + napi_value nModuleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, hapModuleInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &nModuleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "moduleName", nModuleName)); + HILOG_INFO("ConvertHapModuleInfo moduleName=%{public}s.", hapModuleInfo.moduleName.c_str()); + + napi_value nDescription; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, hapModuleInfo.description.c_str(), NAPI_AUTO_LENGTH, &nDescription)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "description", nDescription)); + HILOG_INFO("ConvertHapModuleInfo description=%{public}s.", hapModuleInfo.description.c_str()); + + napi_value ndescriptionId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &ndescriptionId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "descriptionId", ndescriptionId)); + + napi_value nIconPath; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, hapModuleInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &nIconPath)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "iconPath", nIconPath)); + HILOG_INFO("ConvertHapModuleInfo iconPath=%{public}s.", hapModuleInfo.iconPath.c_str()); + + napi_value nIcon; + std::string theIcon = ""; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, theIcon.c_str(), NAPI_AUTO_LENGTH, &nIcon)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "icon", nIcon)); + + napi_value nLabel; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, hapModuleInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "label", nLabel)); + HILOG_INFO("ConvertHapModuleInfo label=%{public}s.", hapModuleInfo.label.c_str()); + + napi_value nLabelId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nLabelId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "labelId", nLabelId)); + + napi_value nIconId; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nIconId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "iconId", nIconId)); + + napi_value nBackgroundImg; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, hapModuleInfo.backgroundImg.c_str(), NAPI_AUTO_LENGTH, &nBackgroundImg)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "backgroundImg", nBackgroundImg)); + HILOG_INFO("ConvertHapModuleInfo backgroundImg=%{public}s.", hapModuleInfo.backgroundImg.c_str()); + + napi_value nSupportedModes; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, hapModuleInfo.supportedModes, &nSupportedModes)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "supportedModes", nSupportedModes)); + + napi_value nReqCapabilities; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nReqCapabilities)); + for (size_t idx = 0; idx < hapModuleInfo.reqCapabilities.size(); idx++) { + napi_value nReqCapabilitie; + NAPI_CALL_RETURN_VOID(env, + napi_create_string_utf8( + env, hapModuleInfo.reqCapabilities[idx].c_str(), NAPI_AUTO_LENGTH, &nReqCapabilitie)); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nReqCapabilities, idx, nReqCapabilitie)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "reqCapabilities", nReqCapabilities)); + + napi_value nDeviceTypes; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nDeviceTypes)); + for (size_t idx = 0; idx < hapModuleInfo.deviceTypes.size(); idx++) { + napi_value nDeviceType; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, hapModuleInfo.deviceTypes[idx].c_str(), NAPI_AUTO_LENGTH, &nDeviceType)); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nDeviceTypes, idx, nDeviceType)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "deviceTypes", nDeviceTypes)); + + napi_value nAbilityInfos; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nAbilityInfos)); + for (size_t idx = 0; idx < hapModuleInfo.abilityInfos.size(); idx++) { + napi_value objAbilityInfo; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objAbilityInfo)); + ConvertAbilityInfo(env, objAbilityInfo, hapModuleInfo.abilityInfos[idx]); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nAbilityInfos, idx, objAbilityInfo)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "abilityInfo", nAbilityInfos)); + + napi_value nColorMode; + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(hapModuleInfo.colorMode), &nColorMode)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "colorMode", nColorMode)); + + napi_value nMainAbilityName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, hapModuleInfo.mainAbility.c_str(), NAPI_AUTO_LENGTH, &nMainAbilityName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "mainAbilityName", nMainAbilityName)); + HILOG_INFO("ConvertHapModuleInfo mainAbilityName=%{public}s.", hapModuleInfo.mainAbility.c_str()); + + napi_value nInstallationFree; + NAPI_CALL_RETURN_VOID(env, napi_get_boolean(env, false, &nInstallationFree)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objHapModuleInfo, "installationFree", nInstallationFree)); +} + static void ConvertBundleInfo(napi_env env, napi_value objBundleInfo, const BundleInfo &bundleInfo) { napi_value nName; @@ -484,7 +651,27 @@ static void ConvertBundleInfo(napi_env env, napi_value objBundleInfo, const Bund ConvertAbilityInfo(env, objAbilityInfo, bundleInfo.abilityInfos[idx]); NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nAbilityInfos, idx, objAbilityInfo)); } - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "abilityInfos", nAbilityInfos)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "abilityInfo", nAbilityInfos)); + + napi_value nAbilityInfoss; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nAbilityInfoss)); + for (size_t idx = 0; idx < bundleInfo.abilityInfos.size(); idx++) { + napi_value objAbilityInfo; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objAbilityInfo)); + ConvertAbilityInfo(env, objAbilityInfo, bundleInfo.abilityInfos[idx]); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nAbilityInfoss, idx, objAbilityInfo)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "abilityInfos", nAbilityInfoss)); + + napi_value nHapModuleInfos; + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nHapModuleInfos)); + for (size_t idx = 0; idx < bundleInfo.hapModuleInfos.size(); idx++) { + napi_value objHapModuleInfo; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objHapModuleInfo)); + ConvertHapModuleInfo(env, objHapModuleInfo, bundleInfo.hapModuleInfos[idx]); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, nHapModuleInfos, idx, objHapModuleInfo)); + } + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "hapModuleInfo", nHapModuleInfos)); napi_value nReqPermissions; NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nReqPermissions)); @@ -516,10 +703,6 @@ static void ConvertBundleInfo(napi_env env, napi_value objBundleInfo, const Bund NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, objBundleInfo, "reqPermissionDetails", nReqPermissionDetails)); - napi_value nHapModuleInfos; - NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &nHapModuleInfos)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objBundleInfo, "hapModuleInfos", nHapModuleInfos)); - napi_value nMinCompatibleVersionCode; NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, DEFAULT_INT32, &nMinCompatibleVersionCode)); NAPI_CALL_RETURN_VOID( @@ -634,10 +817,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 +844,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 +866,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 +876,93 @@ 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, 0, &size) != napi_ok) { + if (napi_get_value_string_utf8(env, value, nullptr, NAPI_RETURN_ZERO, &size) != napi_ok) { HILOG_ERROR("can not get string size"); return ""; } - result.reserve(size + 1); + result.reserve(size + NAPI_RETURN_ONE); result.resize(size); - if (napi_get_value_string_utf8(env, value, result.data(), (size + 1), &size) != napi_ok) { + if (napi_get_value_string_utf8(env, value, result.data(), (size + NAPI_RETURN_ONE), &size) != napi_ok) { HILOG_ERROR("can not get string value"); return ""; } @@ -715,18 +971,17 @@ static std::string GetStringFromNAPI(napi_env env, napi_value value) static napi_value ParseInt(napi_env env, int ¶m, napi_value args) { - napi_status status; - napi_valuetype valuetype; + napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args, &valuetype)); HILOG_INFO("param=%{public}d.", valuetype); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. int32 expected."); - int32_t value; + int32_t value = 0; napi_get_value_int32(env, args, &value); HILOG_INFO("param=%{public}d.", value); param = value; // create result code - napi_value result; - status = napi_create_int32(env, 1, &result); + napi_value result = nullptr; + napi_status status = napi_create_int32(env, NAPI_RETURN_ONE, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -788,15 +1043,23 @@ 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[0]); - ParseInt(env, userId, argv[1]); + ParseInt(env, flag, argv[PARAM0]); + ParseInt(env, userId, argv[PARAM1]); ApplicationFlag applicationFlag = ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS; if (flag == static_cast(ApplicationFlag::GET_BASIC_APPLICATION_INFO)) { applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; } - AsyncApplicationInfosCallbackInfo *asyncCallbackInfo = new AsyncApplicationInfosCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .applicationFlag = applicationFlag, .userId = userId}; + AsyncApplicationInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncApplicationInfosCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .applicationFlag = applicationFlag, + .userId = userId + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { HILOG_INFO("GetApplicationInfos asyncCallback."); napi_value resourceName; @@ -804,7 +1067,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], 1, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -833,12 +1096,21 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetApplicationInfos promise."); @@ -867,23 +1139,33 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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; } } -// QueryAbilityInfo(want) -static bool InnerQueryAbilityInfo(napi_env env, const Want &want, AbilityInfo &abilityInfo) +// QueryAbilityInfos(want) +static bool InnerQueryAbilityInfos(napi_env env, const Want &want, std::vector &abilityInfos) { auto iBundleMgr = GetBundleMgr(); if (!iBundleMgr) { HILOG_ERROR("can not get iBundleMgr"); return false; } - return iBundleMgr->QueryAbilityInfo(want, abilityInfo); + return iBundleMgr->QueryAbilityInfos(want, abilityInfos); } static napi_value ParseWant(napi_env env, Want &want, napi_value args) @@ -934,44 +1216,7 @@ static napi_value ParseWant(napi_env env, Want &want, napi_value args) // create result code napi_value result; - status = napi_create_int32(env, 1, &result); - NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); - return result; -} - -static napi_value ParseQueryParameter(napi_env env, QueryParameter &queryParameter, napi_value args) -{ - napi_status status; - napi_valuetype valueType; - NAPI_CALL(env, napi_typeof(env, args, &valueType)); - NAPI_ASSERT(env, valueType == napi_object, "param type mismatch!"); - HILOG_INFO("-----ParseQueryParameter type-----"); - napi_value queryProp = nullptr; - status = napi_get_named_property(env, args, "params", &queryProp); - NAPI_ASSERT(env, status == napi_ok, "property name incorrect!"); - napi_typeof(env, queryProp, &valueType); - NAPI_ASSERT(env, valueType == napi_object, "property type mismatch!"); - HILOG_INFO("-----ParseQueryParameter QueryParameter-----"); - - napi_value property = nullptr; - status = napi_get_named_property(env, queryProp, "flags", &property); - NAPI_ASSERT(env, status == napi_ok, "property flags incorrect!"); - napi_typeof(env, property, &valueType); - NAPI_ASSERT(env, valueType == napi_number, "property type mismatch!"); - int flags = 0; - NAPI_CALL(env, napi_get_value_int32(env, property, &flags)); - queryParameter.flags = flags; - HILOG_INFO("ParseQueryParameter flags=%{public}d.", queryParameter.flags); - - property = nullptr; - status = napi_get_named_property(env, queryProp, "userId", &property); - NAPI_CALL(env, napi_typeof(env, property, &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "Wrong argument type. String expected."); - queryParameter.userId = GetStringFromNAPI(env, property); - HILOG_INFO("ParseQueryParameter userId=%{public}s.", queryParameter.userId.c_str()); - // create result code - napi_value result; - status = napi_create_int32(env, 1, &result); + status = napi_create_int32(env, NAPI_RETURN_ONE, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -979,33 +1224,43 @@ static napi_value ParseQueryParameter(napi_env env, QueryParameter &queryParamet /** * Promise and async callback */ -napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) +napi_value QueryAbilityInfos(napi_env env, napi_callback_info info) { - HILOG_INFO("QueryAbilityInfo called"); - size_t argc = ARGS_SIZE_THREE; - napi_value argv[ARGS_SIZE_THREE] = {nullptr}; + HILOG_INFO("QueryAbilityInfos called"); + size_t argc = ARGS_SIZE_FOUR; + napi_value argv[ARGS_SIZE_FOUR] = {nullptr}; 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[0]); + ParseWant(env, want, argv[PARAM0]); 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[1]); - AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = - new AsyncAbilityInfoCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr, .want = want}; - - if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { - HILOG_INFO("QueryAbilityInfo asyncCallback."); + int bundleFlags; + int userId; + ParseInt(env, bundleFlags, argv[PARAM1]); + ParseInt(env, userId, argv[PARAM2]); + + AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = new AsyncAbilityInfoCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .want = want + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + if (argc > (ARGS_SIZE_FOUR - CALLBACK_SIZE)) { + HILOG_INFO("QueryAbilityInfos asyncCallback."); napi_valuetype valuetype = napi_undefined; - napi_typeof(env, argv[ARGS_SIZE_TWO], &valuetype); + 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_TWO], 1, &asyncCallbackInfo->callback)); + NAPI_CALL( + env, napi_create_reference(env, argv[ARGS_SIZE_THREE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_value resourceName; - napi_create_string_latin1(env, "QueryAbilityInfo", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "QueryAbilityInfos", NAPI_AUTO_LENGTH, &resourceName); napi_create_async_work( env, nullptr, @@ -1013,7 +1268,7 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) [](napi_env env, void *data) { AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = (AsyncAbilityInfoCallbackInfo *)data; asyncCallbackInfo->ret = - InnerQueryAbilityInfo(env, asyncCallbackInfo->want, asyncCallbackInfo->abilityInfo); + InnerQueryAbilityInfos(env, asyncCallbackInfo->want, asyncCallbackInfo->abilityInfos); }, [](napi_env env, napi_status status, void *data) { AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = (AsyncAbilityInfoCallbackInfo *)data; @@ -1022,8 +1277,8 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) napi_value undefined = 0; napi_value callResult = 0; napi_get_undefined(env, &undefined); - napi_create_object(env, &result[PARAM1]); - ConvertAbilityInfo(env, result[PARAM1], asyncCallbackInfo->abilityInfo); + napi_create_array(env, &result[PARAM1]); + ProcessAbilityInfos(env, result[PARAM1], asyncCallbackInfo->abilityInfos); 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); @@ -1033,44 +1288,64 @@ napi_value QueryAbilityInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { - HILOG_INFO("QueryAbilityInfo promise."); + HILOG_INFO("QueryAbilityInfos 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, "QueryAbilityInfo", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "QueryAbilityInfos", NAPI_AUTO_LENGTH, &resourceName); napi_create_async_work( env, nullptr, resourceName, [](napi_env env, void *data) { AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = (AsyncAbilityInfoCallbackInfo *)data; - InnerQueryAbilityInfo(env, asyncCallbackInfo->want, asyncCallbackInfo->abilityInfo); + InnerQueryAbilityInfos(env, asyncCallbackInfo->want, asyncCallbackInfo->abilityInfos); }, [](napi_env env, napi_status status, void *data) { HILOG_INFO("=================load================="); AsyncAbilityInfoCallbackInfo *asyncCallbackInfo = (AsyncAbilityInfoCallbackInfo *)data; napi_value result; - napi_create_object(env, &result); - ConvertAbilityInfo(env, result, asyncCallbackInfo->abilityInfo); + napi_create_array(env, &result); + ProcessAbilityInfos(env, result, asyncCallbackInfo->abilityInfos); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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 +1371,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, 1, &result); + status = napi_create_int32(env, NAPI_RETURN_ONE, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -1113,26 +1388,31 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) int flag; int userId; std::string bundleName; - ParseString(env, bundleName, argv[0]); - ParseInt(env, flag, argv[1]); - ParseInt(env, userId, argv[2]); + ParseString(env, bundleName, argv[PARAM0]); + ParseInt(env, flag, argv[PARAM1]); + ParseInt(env, userId, argv[PARAM2]); ApplicationFlag applicationFlag = ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS; if (flag == static_cast(ApplicationFlag::GET_BASIC_APPLICATION_INFO)) { applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; } - AsyncApplicationInfoCallbackInfo *asyncCallbackInfo = new AsyncApplicationInfoCallbackInfo{.env = env, + AsyncApplicationInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncApplicationInfoCallbackInfo { + .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .applicationFlag = applicationFlag, - .userId = userId}; - + .userId = userId + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_FOUR - CALLBACK_SIZE)) { HILOG_INFO("GetApplicationInfo asyncCallback."); 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], 1, &asyncCallbackInfo->callback)); + NAPI_CALL( + env, napi_create_reference(env, argv[ARGS_SIZE_THREE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "NAPI_GetApplicationInfoCallBack", NAPI_AUTO_LENGTH, &resourceName); @@ -1170,13 +1450,22 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetApplicationInfo promise."); @@ -1212,10 +1501,20 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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,13 +1564,20 @@ 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[0]); + ParseInt(env, flag, argv[PARAM0]); BundleFlag bundleFlag = BundleFlag::GET_BUNDLE_WITH_ABILITIES; if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfosCallbackInfo *asyncCallbackInfo = new AsyncBundleInfosCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleFlag = bundleFlag}; + AsyncBundleInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfosCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .bundleFlag = bundleFlag + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_TWO - CALLBACK_SIZE)) { HILOG_INFO("GetBundleInfo asyncCallback."); napi_value resourceName; @@ -1279,7 +1585,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], 1, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -1308,12 +1614,22 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("BundleMgr::GetBundleInfos promise."); @@ -1341,13 +1657,24 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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,21 +1701,28 @@ 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[0]); - ParseInt(env, flag, argv[1]); + ParseString(env, bundleName, argv[PARAM0]); + ParseInt(env, flag, argv[PARAM1]); BundleFlag bundleFlag = BundleFlag::GET_BUNDLE_WITH_ABILITIES; if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new AsyncBundleInfoCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .param = bundleName, .bundleFlag = bundleFlag}; - + AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfoCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .param = bundleName, + .bundleFlag = bundleFlag + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { HILOG_INFO("InnerGetBundleInfo 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_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "NAPI_InnerGetBundleInfo", NAPI_AUTO_LENGTH, &resourceName); @@ -1419,13 +1753,22 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetBundleinfo promise."); @@ -1454,10 +1797,20 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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,21 +1841,28 @@ 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[0]); - ParseInt(env, flag, argv[1]); + ParseString(env, hapFilePath, argv[PARAM0]); + ParseInt(env, flag, argv[PARAM1]); BundleFlag bundleFlag = BundleFlag::GET_BUNDLE_WITH_ABILITIES; if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new AsyncBundleInfoCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .param = hapFilePath, .bundleFlag = bundleFlag}; - + AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfoCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .param = hapFilePath, + .bundleFlag = bundleFlag + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { HILOG_INFO("GetBundleArchiveInfo 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_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "NAPI_GetBundleArchiveInfo", NAPI_AUTO_LENGTH, &resourceName); @@ -1533,12 +1893,21 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetBundleArchiveInfo promise."); @@ -1567,10 +1936,20 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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,16 +2038,22 @@ 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[0]); - AsyncPermissionDefCallbackInfo *asyncCallbackInfo = new AsyncPermissionDefCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .permissionName = permissionName}; - + ParseString(env, permissionName, argv[PARAM0]); + AsyncPermissionDefCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncPermissionDefCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .permissionName = permissionName + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_TWO - CALLBACK_SIZE)) { HILOG_INFO("GetPermissionDef 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_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_value resourceName; napi_create_string_latin1(env, "GetPermissionDef", NAPI_AUTO_LENGTH, &resourceName); @@ -1699,12 +2084,21 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { napi_deferred deferred; @@ -1731,10 +2125,20 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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; } } @@ -1782,14 +2186,20 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); AsyncGetBundleInstallerCallbackInfo *asyncCallbackInfo = - new AsyncGetBundleInstallerCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; - + new AsyncGetBundleInstallerCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_ONE - CALLBACK_SIZE)) { HILOG_INFO("GetBundleInstaller asyncCallback."); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &asyncCallbackInfo->callback); + napi_create_reference(env, argv[PARAM0], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); napi_value resourceName; napi_create_string_latin1(env, "GetBundleInstaller", NAPI_AUTO_LENGTH, &resourceName); @@ -1814,12 +2224,21 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { napi_deferred deferred; @@ -1842,10 +2261,20 @@ napi_value GetBundleInstaller(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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 +2303,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, "installFlag", &property); + NAPI_ASSERT(env, status == napi_ok, "property installFlag incorrect!"); + napi_typeof(env, property, &valueType); + NAPI_ASSERT(env, valueType == napi_number, "property type mismatch!"); + int installFlag = 0; + NAPI_CALL(env, napi_get_value_int32(env, property, &installFlag)); + installParam.installFlag = static_cast(installFlag); + HILOG_INFO("ParseInstallParam installFlag=%{public}d.", installParam.installFlag); + property = nullptr; status = napi_get_named_property(env, installProp, "isKeepData", &property); NAPI_ASSERT(env, status == napi_ok, "property isKeepData incorrect!"); @@ -1885,7 +2324,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, 1, &result); + status = napi_create_int32(env, NAPI_RETURN_ONE, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -1899,7 +2338,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 +2352,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, 1, &result); + status = napi_create_int32(env, NAPI_RETURN_ONE, &result); NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); return result; } @@ -1978,17 +2417,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,23 +2456,25 @@ 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[0]); + ParseStringArray(env, bundleFilePaths, argv[PARAM0]); InstallParam installParam; - ParseInstallParam(env, installParam, argv[1]); - AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ + ParseInstallParam(env, installParam, argv[PARAM1]); + AsyncInstallCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncInstallCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, .hapFiles = bundleFilePaths, .installParam = installParam, }; - + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { HILOG_INFO("Install asyncCallback."); 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], 1, &asyncCallbackInfo->callback); + napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); napi_value resourceName; napi_create_string_latin1(env, "Install", NAPI_AUTO_LENGTH, &resourceName); @@ -2070,12 +2515,21 @@ napi_value Install(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { napi_deferred deferred; @@ -2112,10 +2566,20 @@ napi_value Install(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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,23 +2620,25 @@ 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[0]); + ParseString(env, bundleName, argv[PARAM0]); InstallParam installParam; - ParseInstallParam(env, installParam, argv[1]); - AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ + ParseInstallParam(env, installParam, argv[PARAM1]); + AsyncInstallCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncInstallCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, .param = bundleName, .installParam = installParam, }; - + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { HILOG_INFO("Uninstall asyncCallback."); 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], 1, &asyncCallbackInfo->callback); + napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback); napi_value resourceName; napi_create_string_latin1(env, "Uninstall", NAPI_AUTO_LENGTH, &resourceName); @@ -2211,14 +2677,22 @@ napi_value Uninstall(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); - + 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)); return result; } else { napi_deferred deferred; @@ -2253,10 +2727,20 @@ napi_value Uninstall(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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; } } @@ -2308,16 +2792,22 @@ napi_value GetAllFormsInfo(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); - AsyncFormInfosCallbackInfo *asyncCallbackInfo = - new AsyncFormInfosCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; + AsyncFormInfosCallbackInfo *asyncCallbackInfo = new AsyncFormInfosCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_ONE - CALLBACK_SIZE)) { HILOG_INFO("GetAllFormsInfo asyncCallback."); 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[0], &valuetype); + napi_typeof(env, argv[PARAM0], &valuetype); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - NAPI_CALL(env, napi_create_reference(env, argv[0], 1, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[PARAM0], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2345,12 +2835,22 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetFormInfos promise."); @@ -2378,10 +2878,20 @@ napi_value GetAllFormsInfo(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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,11 +2919,19 @@ 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[0]); - ParseString(env, moduleName, argv[1]); - - AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByModuleCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .moduleName = moduleName}; + ParseString(env, bundleName, argv[PARAM0]); + ParseString(env, moduleName, argv[PARAM1]); + + AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByModuleCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .bundleName = bundleName, + .moduleName = moduleName + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_THREE - CALLBACK_SIZE)) { HILOG_INFO("GetFormsInfoByModule asyncCallback."); napi_value resourceName; @@ -2421,7 +2939,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], 1, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_TWO], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2450,12 +2968,21 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetFormsInfoByModule promise."); @@ -2484,10 +3011,20 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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,10 +3051,17 @@ 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[0]); + ParseString(env, bundleName, argv[PARAM0]); - AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByAppCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; + AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByAppCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .bundleName = bundleName + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_TWO - CALLBACK_SIZE)) { HILOG_INFO("GetFormsInfoByApp asyncCallback."); napi_value resourceName; @@ -2525,7 +3069,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], 1, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2554,12 +3098,21 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetFormsInfoByApp promise."); @@ -2587,15 +3140,26 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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 +3178,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,9 +3200,16 @@ 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[0]); - AsyncShortcutInfosCallbackInfo *asyncCallbackInfo = new AsyncShortcutInfosCallbackInfo{ - .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; + ParseString(env, bundleName, argv[PARAM0]); + AsyncShortcutInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncShortcutInfosCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .bundleName = bundleName + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } if (argc > (ARGS_SIZE_TWO - CALLBACK_SIZE)) { HILOG_INFO("GetShortcutInfos asyncCallback."); napi_value resourceName; @@ -2645,7 +3217,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], 1, &asyncCallbackInfo->callback)); + NAPI_CALL(env, napi_create_reference(env, argv[ARGS_SIZE_ONE], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); napi_create_async_work( env, @@ -2674,12 +3246,21 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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)); + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ONE, &result)); return result; } else { HILOG_INFO("GetShortcutInfos promise."); @@ -2707,10 +3288,697 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }, (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[PARAM0]); + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncModuleUsageRecordsCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .number = number + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + 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], NAPI_RETURN_ONE, &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; + asyncCallbackInfo = nullptr; + }, + (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)); + 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; + asyncCallbackInfo = nullptr; + }, + (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 = nullptr; + napi_status status = napi_ok; + status = napi_create_int32(env, NAPI_RETURN_ONE, &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[PARAM0]); + if (permissionEvent == PERMISSION_CHANGE && argc == ARGS_SIZE_THREE) { + std::vector uids; + ParseInt32Array(env, uids, argv[ARGS_SIZE_ONE]); + AsyncRegisterPermissions *asyncCallbackInfo = new (std::nothrow) AsyncRegisterPermissions { + .env = env, + .asyncWork = nullptr, + .uids = uids + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + 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], NAPI_RETURN_ONE, &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; + asyncCallbackInfo = nullptr; + }, + (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)); + return result; + } else if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { + AsyncRegisterAllPermissions *asyncCallbackInfo = new (std::nothrow) AsyncRegisterAllPermissions { + .env = env, + .asyncWork = nullptr + }; + if (asyncCallbackInfo == nullptr) { + return 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], NAPI_RETURN_ONE, &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; + asyncCallbackInfo = nullptr; + }, + (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)); + return result; + } + + napi_value result; + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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 ret = iBundleMgr->UnregisterPermissionsChanged(item.second); + if (!ret) { + 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 ret = iBundleMgr->UnregisterPermissionsChanged(item.second); + if (!ret) { + HILOG_ERROR("InnerUnregisterPermissionsChanged call error"); + return false; + } + HILOG_INFO("call UnregisterPermissionsChanged success = %{public}zu.", 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[PARAM0]); + + if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { + AsyncUnregisterPermissions *asyncCallbackInfo = new (std::nothrow) AsyncUnregisterPermissions { + .env = env, + .asyncWork = nullptr, + }; + if (asyncCallbackInfo == nullptr) { + return 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], NAPI_RETURN_ONE, &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; + asyncCallbackInfo = nullptr; + }, + (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)); + 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 + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + 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], NAPI_RETURN_ONE, &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; + asyncCallbackInfo = nullptr; + }, + (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)); + return result; + } + napi_value result; + NAPI_CALL(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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[PARAM0]); + std::string permission; + ParseString(env, permission, argv[PARAM1]); + + AsyncPermissionCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncPermissionCallbackInfo { + .env = env, + .asyncWork = nullptr, + .deferred = nullptr, + .bundleName = bundleName, + .permission = permission + }; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + 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], NAPI_RETURN_ONE, &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; + asyncCallbackInfo = nullptr; + }, + (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)); + 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; + asyncCallbackInfo = nullptr; + }, + (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 +4002,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, 0, &nUnspecified)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 1, &nCa)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &nCa)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "CA", nCa)); } @@ -2776,68 +4044,69 @@ 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, 0, &nFlagModuleUpgradeCheck)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 1, &nFlagModuleUpgradeInstall)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &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, 2, &nFlagModuleUpgradeinstallWithConfigWindows)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &nFlagModuleUpgradeinstallWithConfigWindows)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property( - env, value, "FLAG_MODULE_UPGRADE_INSTALL_WITH_CONFIG_WINDOWS", nFlagModuleUpgradeinstallWithConfigWindows)); + env, value, "FLAG_MODULE_UPGRADE_INSTALL_WITH_CONFIG_WINDOWS", + nFlagModuleUpgradeinstallWithConfigWindows)); } void CreateFormTypeObject(napi_env env, napi_value value) { napi_value nJava; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, 0, &nJava)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 1, &nJs)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &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, -1, &nAutoMode)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_FAILED, &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, 0, &nDarkMode)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 1, &nLightMode)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &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, -1, &nPermissionDenied)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_FAILED, &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, 0, &nPermissionGranted)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 0, &nFlagModuleNotUsedByForm)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 1, &nFlagModuleUsedByForm)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &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, 2, &nFlagModuleNotUsedByShortcut)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &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, 3, &nFlagModuleUsedByShortcut)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_THREE, &nFlagModuleUsedByShortcut)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "FLAG_MODULE_USED_BY_SHORTCUT", nFlagModuleUsedByShortcut)); } @@ -2845,13 +4114,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, 0, &nSignatureMatched)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 1, &nSignatureNotMatched)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &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, 2, &nSignatureUnknownBundle)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &nSignatureUnknownBundle)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "SIGNATURE_UNKNOWN_BUNDLE", nSignatureUnknownBundle)); } @@ -2859,15 +4128,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, 0, &nShortcutExistenceExists)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &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, 1, &nShortcutExistenceNotExists)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ONE, &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, 2, &nShortcutExistenceUnknow)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_TWO, &nShortcutExistenceUnknow)); NAPI_CALL_RETURN_VOID( env, napi_set_named_property(env, value, "SHORTCUT_EXISTENCE_UNKNOW", nShortcutExistenceUnknow)); } @@ -2875,7 +4144,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, 0, &nQueryShortCutHome)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, NAPI_RETURN_ZERO, &nQueryShortCutHome)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "QUERY_SHORTCUT_HOME", nQueryShortCutHome)); } @@ -2886,7 +4155,8 @@ void CreateInstallErrorCodeObject(napi_env env, napi_value value) NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "SUCCESS", nSuccess)); napi_value nStatusInstallFailure; NAPI_CALL_RETURN_VOID(env, - napi_create_int32(env, static_cast(InstallErrorCode::STATUS_INSTALL_FAILURE), &nStatusInstallFailure)); + napi_create_int32( + env, static_cast(InstallErrorCode::STATUS_INSTALL_FAILURE), &nStatusInstallFailure)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "STATUS_INSTALL_FAILURE", nStatusInstallFailure)); napi_value nStatusInstallFailureAborted; NAPI_CALL_RETURN_VOID(env, @@ -2949,7 +4219,8 @@ void CreateInstallErrorCodeObject(napi_env env, napi_value value) static_cast(InstallErrorCode::STATUS_UNINSTALL_FAILURE_CONFLICT), &nStatusUninstallFailureConflict)); NAPI_CALL_RETURN_VOID( - env, napi_set_named_property(env, value, "STATUS_UNINSTALL_FAILURE_CONFLICT", nStatusUninstallFailureConflict)); + env, napi_set_named_property( + env, value, "STATUS_UNINSTALL_FAILURE_CONFLICT", nStatusUninstallFailureConflict)); napi_value nStatusInstallFailureDownloadTimeout; NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, @@ -2970,7 +4241,8 @@ void CreateInstallErrorCodeObject(napi_env env, napi_value value) NAPI_CALL_RETURN_VOID(env, napi_create_int32( env, static_cast(InstallErrorCode::STATUS_ABILITY_NOT_FOUND), &nStatusAbilityNotFound)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, value, "STATUS_ABILITY_NOT_FOUND", nStatusAbilityNotFound)); + NAPI_CALL_RETURN_VOID( + env, napi_set_named_property(env, value, "STATUS_ABILITY_NOT_FOUND", nStatusAbilityNotFound)); napi_value nBmsServiceError; NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, static_cast(InstallErrorCode::STATUS_BMS_SERVICE_ERROR), &nBmsServiceError)); diff --git a/kits/appkit/napi/bundlemgr/bundle_mgr.h b/kits/appkit/napi/bundlemgr/bundle_mgr.h index e3625bcd718135ede73b30e45d0c1a41abbad067..d8c01e8db94c987914262bd60cfed583de9a9810 100644 --- a/kits/appkit/napi/bundlemgr/bundle_mgr.h +++ b/kits/appkit/napi/bundlemgr/bundle_mgr.h @@ -36,7 +36,7 @@ struct AsyncAbilityInfoCallbackInfo { napi_deferred deferred; napi_ref callback = 0; OHOS::AAFwk::Want want; - OHOS::AppExecFwk::AbilityInfo abilityInfo; + std::vector abilityInfos; bool ret = false; }; @@ -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,11 +167,42 @@ 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); +napi_value GetApplicationInfos(napi_env env, napi_callback_info info); napi_value GetApplicationInfo(napi_env env, napi_callback_info info); -napi_value QueryAbilityInfo(napi_env env, napi_callback_info info); +napi_value QueryAbilityInfos(napi_env env, napi_callback_info info); napi_value GetBundleInfos(napi_env env, napi_callback_info info); napi_value GetBundleInfo(napi_env env, napi_callback_info info); napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info 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..dc62bcdc96a895d8df87f8f3fdbc12c87138b2f7 100644 --- a/kits/appkit/napi/bundlemgr/native_module.cpp +++ b/kits/appkit/napi/bundlemgr/native_module.cpp @@ -82,18 +82,24 @@ static napi_value Init(napi_env env, napi_value exports) * Propertise define */ napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getAllApplicationInfo", GetApplicationInfos), DECLARE_NAPI_FUNCTION("getApplicationInfos", GetApplicationInfos), DECLARE_NAPI_FUNCTION("getApplicationInfo", GetApplicationInfo), + DECLARE_NAPI_FUNCTION("getAllBundleInfo", GetBundleInfos), DECLARE_NAPI_FUNCTION("getBundleInfos", GetBundleInfos), DECLARE_NAPI_FUNCTION("getBundleInfo", GetBundleInfo), DECLARE_NAPI_FUNCTION("getBundleArchiveInfo", GetBundleArchiveInfo), DECLARE_NAPI_FUNCTION("getPermissionDef", GetPermissionDef), - DECLARE_NAPI_FUNCTION("queryAbilityByWant", QueryAbilityInfo), + DECLARE_NAPI_FUNCTION("queryAbilityByWant", QueryAbilityInfos), DECLARE_NAPI_FUNCTION("getBundleInstaller", GetBundleInstaller), DECLARE_NAPI_FUNCTION("getFormsInfoByModule", GetFormsInfoByModule), DECLARE_NAPI_FUNCTION("getFormsInfo", GetFormsInfoByApp), DECLARE_NAPI_FUNCTION("getAllFormsInfo", GetAllFormsInfo), - DECLARE_NAPI_FUNCTION("getShortcutInfos", GetShortcutInfos), + DECLARE_NAPI_FUNCTION("getAllShortcutInfo", 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..071b8d8c6f9bbd429f8019641cb13dd60dcb376d --- /dev/null +++ b/kits/appkit/napi/bundlemgr/permission_callback.cpp @@ -0,0 +1,100 @@ +/* + * 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 "napi/native_common.h" +#include "permission_callback.h" +#include "hilog_wrapper.h" + +namespace { +constexpr size_t ARGS_SIZE_TWO = 2; +} + +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 + if (loop == nullptr) { + HILOG_INFO("loop instance is nullptr"); + return; + } + + uv_work_t *work = new (std::nothrow) uv_work_t; + if (work == nullptr) { + HILOG_ERROR("new uv_work_t failed"); + return; + } + CallbackInfo *callbackInfo = new (std::nothrow) CallbackInfo{ + .env = env_, + .callback = callback_, + .uid = uid, + }; + if (callbackInfo == nullptr) { + HILOG_ERROR("new CallbackInfo failed"); + return; + } + work->data = (void *)callbackInfo; + + int rev = 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, ARGS_SIZE_TWO, &result[0], &callbackResult); + delete event; + event = nullptr; + delete work; + work = nullptr; + }); + if (rev != 0) { + if (callbackInfo != nullptr) { + delete callbackInfo; + } + if (work != nullptr) { + 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/app_loader.h b/kits/appkit/native/app/include/app_loader.h index a1197ca895bb38ecf4adada31bfc2377bc4a32e6..5b751c7e1d452dc97391331562d05b7d3752714b 100644 --- a/kits/appkit/native/app/include/app_loader.h +++ b/kits/appkit/native/app/include/app_loader.h @@ -80,7 +80,7 @@ private: __attribute__((constructor)) void REGISTER_APPLICATION##className() \ { \ ApplicationLoader::GetInstance().RegisterApplication( \ - #bundleName, []() -> OHOSApplication * { return new (std::nothrow) className; }); \ + #bundleName, []()->OHOSApplication * { return new (std::nothrow) className; }); \ } } // namespace AppExecFwk 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/include/main_thread.h b/kits/appkit/native/app/include/main_thread.h index 21f43ad89a418f91edd8abb71fbf82f27a325443..fda5783d3e80de134215766a0f195916544e3d7d 100644 --- a/kits/appkit/native/app/include/main_thread.h +++ b/kits/appkit/native/app/include/main_thread.h @@ -24,13 +24,16 @@ #include "app_mgr_interface.h" #include "ability_record_mgr.h" #include "application_impl.h" +#include "resource_manager.h" #include "ohos/aafwk/base/ipc_singleton.h" #define ABILITY_LIBRARY_LOADER namespace OHOS { namespace AppExecFwk { +using namespace OHOS::Global; enum class MainThreadState { INIT, ATTACH, READY, RUNNING }; - +class ContextDeal; +// class Global::Resource::ResourceManager; class AppMgrDeathRecipient : public IRemoteObject::DeathRecipient { public: /** @@ -400,6 +403,8 @@ private: */ void LoadAbilityLibrary(const std::vector &libraryPaths); + void LoadAppLibrary(); + /** * * @brief Close the ability library loaded. @@ -427,6 +432,12 @@ private: * */ bool CheckFileType(const std::string &fileName, const std::string &extensionName); + + bool InitCreate(std::shared_ptr &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo, + Profile &appProfile); + bool CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData); + bool InitResourceManager(std::shared_ptr &resourceManager, + std::shared_ptr &contextDeal, ApplicationInfo &appInfo); std::vector fileEntries_; std::vector handleAbilityLib_; // the handler of ACE Library. #endif // ABILITY_LIBRARY_LOADER diff --git a/kits/appkit/native/app/include/task_dispatcher.h b/kits/appkit/native/app/include/task_dispatcher.h index ad06df59eaaef82f64d2164e337864277e2cf3dd..4ddee5b9834a4da0693ac826be2a3504b8d28c2e 100644 --- a/kits/appkit/native/app/include/task_dispatcher.h +++ b/kits/appkit/native/app/include/task_dispatcher.h @@ -25,7 +25,7 @@ namespace OHOS { namespace AppExecFwk { -template +template using IteratableTask = std::function; class TaskDispatcher { @@ -33,31 +33,15 @@ public: virtual ~TaskDispatcher() = default; /** - * Dispatches a task and waits until the task is complete in the current thread. + * @brief Dispatches a task and waits until the task is complete in the current thread. * - *

The current thread is blocked before the given task is complete. Therefore, a deadlock occurs in the - * following cases: - *

- *
    - *
  1. - * {@code SyncDispatch} is cyclically called on a serial task dispatcher or a task dispatcher that is dedicated - * to a specific thread. For example, {@code SyncDispatch} is called to dispatch a task from dispatcher A to - * dispatcher A, or to dispatch a task from dispatcher A to dispatcher B and then back to dispatcher A. - *
  2. - *
  3. - * Too many threads are blocked on {@code SyncDispatch}. As a result, the internal thread pool is used up and - * cannot process other tasks any more. - *
  4. - *
- *
* @param runnable Indicates the task to be executed. This parameter includes all information required for the task * execution. - * @since 1 */ virtual ErrCode SyncDispatch(const std::shared_ptr &runnable) = 0; /** - * Asynchronously dispatches a task. + * @brief Asynchronously dispatches a task. * *

This method dispatches a task and returns a value immediately without waiting for the task to execute.

* @@ -65,12 +49,11 @@ public: * execution. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable) = 0; /** - * Dispatches a task after the given delay. + * @brief Dispatches a task after the given delay. * *

This is an asynchronous execution and returns a value immediately without waiting. The task will be * dispatched to the queue after the given delay specified by {@code delayMs}, and its actual execution time @@ -83,12 +66,11 @@ public: * @param delayMs Indicates the time period that the given task has to wait before being dispatched. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs) = 0; /** - * Sets an execution barrier in a task group for the given task and waits for the task to be executed after all + * @brief Sets an execution barrier in a task group for the given task and waits for the task to be executed after all * tasks in the task group are finished. * *

The current thread is blocked until the given task is complete. Incorrect use of this method may cause a @@ -96,12 +78,11 @@ public: * If too many threads are blocked, resources in the thread pool will be used up.

* * @param runnable Indicates the task to be executed. - * @since 1 */ virtual ErrCode SyncDispatchBarrier(const std::shared_ptr &runnable) = 0; /** - * Sets an execution barrier for the given task to be executed only after all tasks in the task group are + * @brief Sets an execution barrier for the given task to be executed only after all tasks in the task group are * finished. This method does not wait for the given task to execute. * *

Task execution barriers are unavailable on global task dispatchers. Example code for setting a task @@ -122,21 +103,17 @@ public: * std::cout << "after barrier" << std::endl; * })); * - * // Result will be: - * // before barrier - * // Barrier - * // after barrier + * // Result will be: 1.before barrier; 2.Barrier; 3.after barrier. * } * * * @param runnable Indicates the task to be executed. This parameter includes all information required for the task * execution. - * @since 1 */ virtual ErrCode AsyncDispatchBarrier(const std::shared_ptr &runnable) = 0; /** - * Creates a task group. + * @brief Creates a task group. * *

The {@link std::shared_ptr} object returned by this method does not contain any task. * If you need to dispatch tasks asynchronously, you can use {@link #asyncGroupDispatch} to associate this object @@ -170,21 +147,12 @@ public: * std::cout << "2" << std::endl; * } * - * //Possible results are as follows: - * // 1 - * // 2 - * // Finished downloading URL 2 - * // Finished downloading URL 1 - * // All tasks finished. Do shutdown. - * } - * * @return Returns a {@link std::shared_ptr} object. - * @since 1 */ virtual std::shared_ptr CreateDispatchGroup() = 0; /** - * Adds a task to a task group asynchronously. + * @brief Adds a task to a task group asynchronously. * *

This method returns a value immediately without waiting for the task to execute.

* @@ -193,55 +161,34 @@ public: * execution. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr AsyncGroupDispatch( const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; /** - * Waits all tasks in a task group to finish. + * @brief Waits all tasks in a task group to finish. * * @param group Indicates the task group containing the waiting tasks. * @param timeout Indicates the maximum waiting time for a task. * @return Returns {@code true} if all tasks are correctly executed; returns {@code false} if any task times out. - * @since 1 */ virtual bool GroupDispatchWait(const std::shared_ptr &group, long timeout) = 0; /** - * Executes a task after all tasks in the task group are finished. + * @brief Executes a task after all tasks in the task group are finished. * * @param group Indicates the task group containing the waiting tasks. * @param runnable Indicates the task to be executed after all tasks are finished. - * @since 1 */ virtual ErrCode GroupDispatchNotify( const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; /** - * Executes a task multiple times without waiting. - * - *

Example code: - *

{@code
-     * std::string names[] = {"Rafael Nadal", "Novak Djokovic",
-     *         "Stanislas Wawrinka",
-     *         "David Ferrer","Roger Federer",
-     *         "Andy Murray","Tomas Berdych",
-     *         "Juan Martin Del Potro"};
-     * int num = atp.length;
-     * std::shared_ptr dispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
-     * // Concurrently dispatches tasks using names in |names|.
-     * dispatcher->ApplyDispatch([](i) {
-     *     std::cout << names[i] << std::endl;
-     * }, num);
-     * // The result to be returned depends on thread scheduling of the system.
-     * }
-     * 
+ * @brief Executes a task multiple times without waiting. * * @param task Indicates the task to be executed. This parameter includes all information required for the task * execution. * @param iterations Indicates the number of times the task is executed. The value must be a positive integer. - * @since 1 */ virtual ErrCode ApplyDispatch(const std::shared_ptr> &task, long iterations) = 0; }; 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..861a209ad9ac3bbd3fae0cef694b41f0bb0fff78 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"); } /** @@ -707,9 +737,11 @@ sptr ContextDeal::GetToken() */ void ContextDeal::initResourceManager(const std::shared_ptr &resourceManager) { + APP_LOGI("ContextDeal::initResourceManager. Start."); resourceManager_ = resourceManager; + APP_LOGI("ContextDeal::initResourceManager. End."); } - + /** * @brief Obtains information about the caller of this ability. * @@ -738,19 +770,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 +798,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 +826,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 +852,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 +867,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 +882,15 @@ 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 +901,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 +920,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"); } /** @@ -896,7 +948,6 @@ int ContextDeal::GetThemeId() { auto hapModInfo = GetHapModuleInfo(); if (hapModInfo != nullptr) { - // return hapModInfo->themeId; return -1; } else { APP_LOGE("ContextDeal::GetThemeId hapModInfo is nullptr"); @@ -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..b04a2c5182572b7f6447f7e00780307b5918e494 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,72 +539,46 @@ void MainThread::HandleProcessSecurityExit() } HandleTerminateApplicationLocal(); + APP_LOGI("MainThread::HandleProcessSecurityExit called end."); } -/** - * - * @brief Launch the application. - * - * @param appLaunchData The launchdata of the application witch launced. - * - */ -void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) +bool MainThread::InitCreate( + std::shared_ptr &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo, Profile &appProfile) { - APP_LOGI("MainThread::handleLaunchApplication called"); - if (application_ != nullptr) { - APP_LOGE("MainThread::handleLaunchApplication already create application"); - return; - } - - if (!CheckLaunchApplicationParam(appLaunchData)) { - APP_LOGE("MainThread::handleLaunchApplication appLaunchData invalid"); - return; - } - -#ifdef ABILITY_LIBRARY_LOADER - LoadAbilityLibrary(appLaunchData.GetApplicationInfo().moduleSourceDirs); -#endif // ABILITY_LIBRARY_LOADER -#ifdef APPLICATION_LIBRARY_LOADER - std::string appPath = applicationLibraryPath; - 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); - } -#endif // APPLICATION_LIBRARY_LOADER - - ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); - ProcessInfo processInfo = appLaunchData.GetProcessInfo(); - Profile appProfile = appLaunchData.GetProfile(); - applicationInfo_ = std::make_shared(appInfo); if (applicationInfo_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create applicationInfo_ failed"); - return; + APP_LOGE("MainThread::InitCreate create applicationInfo_ failed"); + return false; } processInfo_ = std::make_shared(processInfo); if (processInfo_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create processInfo_ failed"); - return; + APP_LOGE("MainThread::InitCreate create processInfo_ failed"); + return false; } appProfile_ = std::make_shared(appProfile); if (appProfile_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create appProfile_ failed"); - return; + APP_LOGE("MainThread::InitCreate create appProfile_ failed"); + return false; } applicationImpl_ = std::make_shared(); if (applicationImpl_ == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create applicationImpl_ failed"); - return; + APP_LOGE("MainThread::InitCreate create applicationImpl_ failed"); + return false; + } + + abilityRecordMgr_ = std::make_shared(); + if (abilityRecordMgr_ == nullptr) { + APP_LOGE("MainThread::InitCreate create AbilityRecordMgr failed"); + return false; } - std::shared_ptr contextDeal = std::make_shared(); + contextDeal = std::make_shared(); if (contextDeal == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create contextDeal failed"); - return; + APP_LOGE("MainThread::InitCreate create contextDeal failed"); + return false; } contextDeal->SetProcessInfo(processInfo_); @@ -584,27 +586,33 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) contextDeal->SetProfile(appProfile_); contextDeal->SetBundleCodePath(applicationInfo_->codePath); // BMS need to add cpath - // BMS should set the type (native or ace) of application - bool isNativeApp = true; - std::string appName = isNativeApp ? appInfo.name : aceApplicationName_; - application_ = std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName(appName)); - if (application_ == nullptr) { - APP_LOGE("HandleLaunchApplication::application launch failed"); - return; + return true; +} + +bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData) +{ + if (application_ != nullptr) { + APP_LOGE("MainThread::handleLaunchApplication already create application"); + return false; } - // init resourceManager. - std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); - if (resourceManager == nullptr) { - APP_LOGE("MainThread::handleLaunchApplication create resourceManager failed"); - return; + if (!CheckLaunchApplicationParam(appLaunchData)) { + APP_LOGE("MainThread::handleLaunchApplication appLaunchData invalid"); + return false; } + return true; +} +bool MainThread::InitResourceManager(std::shared_ptr &resourceManager, + std::shared_ptr &contextDeal, ApplicationInfo &appInfo) +{ + APP_LOGI("MainThread::InitResourceManager. Start calling GetBundleManager."); sptr bundleMgr = contextDeal->GetBundleManager(); if (bundleMgr == nullptr) { APP_LOGE("MainThread::handleLaunchApplication GetBundleManager is nullptr"); - return; + return false; } + APP_LOGI("MainThread::handleLaunchApplication. End calling GetBundleManager."); BundleInfo bundleInfo; APP_LOGI("MainThread::handleLaunchApplication length: %{public}zu, bundleName: %{public}s", @@ -612,19 +620,24 @@ 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,33 +649,83 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) APP_LOGI("MainThread::handleLaunchApplication localeInfo is nullptr."); } + APP_LOGI("MainThread::handleLaunchApplication. Start calling UpdateResConfig."); resourceManager->UpdateResConfig(*resConfig); - contextDeal->initResourceManager(resourceManager); - contextDeal->SetApplicationContext(application_); - application_->AttachBaseContext(contextDeal); + APP_LOGI("MainThread::handleLaunchApplication. End calling UpdateResConfig."); + return true; +} +/** + * + * @brief Launch the application. + * + * @param appLaunchData The launchdata of the application witch launced. + * + */ +void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData) +{ + APP_LOGI("MainThread::handleLaunchApplication called start."); + if (!CheckForHandleLaunchApplication(appLaunchData)) { + APP_LOGE("MainThread::handleLaunchApplication CheckForHandleLaunchApplication failed"); + return; + } + LoadAbilityLibrary(appLaunchData.GetApplicationInfo().moduleSourceDirs); + LoadAppLibrary(); - abilityRecordMgr_ = std::make_shared(); - if (abilityRecordMgr_ == nullptr) { - APP_LOGE("HandleLaunchApplication::application create AbilityRecordMgr failed"); + ApplicationInfo appInfo = appLaunchData.GetApplicationInfo(); + ProcessInfo processInfo = appLaunchData.GetProcessInfo(); + Profile appProfile = appLaunchData.GetProfile(); + + std::shared_ptr contextDeal = nullptr; + if (!InitCreate(contextDeal, appInfo, processInfo, appProfile)) { + APP_LOGE("MainThread::handleLaunchApplication InitCreate failed"); return; } + // BMS should set the type (native or ace) of application + bool isNativeApp = true; + std::string appName = isNativeApp ? appInfo.name : aceApplicationName_; + application_ = std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName(appName)); + if (application_ == nullptr) { + APP_LOGE("HandleLaunchApplication::application launch failed"); + return; + } + + // init resourceManager. + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (resourceManager == nullptr) { + APP_LOGE("MainThread::handleLaunchApplication create resourceManager failed"); + return; + } + + if (!InitResourceManager(resourceManager, contextDeal, appInfo)) { + APP_LOGE("MainThread::handleLaunchApplication InitResourceManager failed"); + return; + } + + contextDeal->initResourceManager(resourceManager); + contextDeal->SetApplicationContext(application_); + application_->AttachBaseContext(contextDeal); application_->SetAbilityRecordMgr(abilityRecordMgr_); 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 +737,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 +775,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 +795,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 +833,7 @@ void MainThread::HandleCleanAbilityLocal(const sptr &token) APP_LOGW("MainThread::HandleCleanAbilityLocal runner not found"); } #endif + APP_LOGI("MainThread::HandleCleanAbilityLocal called end."); } /** @@ -776,7 +845,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 +883,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 +896,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 +907,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 +920,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 +931,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 +945,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 +986,7 @@ void MainThread::HandleTerminateApplication() handleAppLib_ = nullptr; } #endif // APPLICATION_LIBRARY_LOADER + APP_LOGI("MainThread::handleTerminateApplication called end."); } /** @@ -910,7 +998,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 +1006,7 @@ void MainThread::HandleShrinkMemory(const int level) } applicationImpl_->PerformMemoryLevel(level); + APP_LOGI("MainThread::HandleShrinkMemory called end."); } /** @@ -929,7 +1018,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 +1026,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 +1040,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 +1060,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 +1074,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 +1100,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 +1120,12 @@ bool MainThread::IsApplicationReady() const */ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths) { +#ifdef ABILITY_LIBRARY_LOADER + 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,13 +1133,19 @@ 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()); + } + libraryPath = libraryPath + "/libs"; if (!ScanDir(libraryPath)) { APP_LOGE("Fail to scanDir %{public}s", libraryPath.c_str()); - continue; } } @@ -1047,7 +1157,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 +1169,22 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths handleAbilityLib_.emplace_back(handleAbilityLib); } } + APP_LOGI("MainThread::LoadAbilityLibrary called end."); +#endif // ABILITY_LIBRARY_LOADER +} + +void MainThread::LoadAppLibrary() +{ +#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 } /** @@ -1066,14 +1194,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,33 +1217,41 @@ 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()); + APP_LOGE("MainThread::ScanDir open dir:%{public}s fail", dirPath.c_str()); return false; } - + APP_LOGI("MainThread::ScanDir after opendir."); struct dirent *df = nullptr; - for (;;) { + for (; ; ) { + APP_LOGI("MainThread::ScanDir before readdir."); df = readdir(dirp); + APP_LOGI("MainThread::ScanDir after readdir."); if (df == nullptr) { break; } std::string currentName(df->d_name); - APP_LOGD("folder found:'%{private}s'", df->d_name); + APP_LOGD("folder found:'%{public}s'", df->d_name); if (currentName.compare(".") == 0 || currentName.compare("..") == 0) { continue; } if (CheckFileType(currentName, abilityLibraryType_)) { + APP_LOGI("MainThread::ScanDir CheckFileType == true."); fileEntries_.emplace_back(dirPath + pathSeparator_ + currentName); } } + 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 +1267,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 +1283,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/app/src/ohos_application.cpp b/kits/appkit/native/app/src/ohos_application.cpp index dd11ac95de1c4ebdb26ffa54fd7812b9d7304a8e..b0155a9a0f2ce9dd7c66ac33fd5e91d8daeb7844 100644 --- a/kits/appkit/native/app/src/ohos_application.cpp +++ b/kits/appkit/native/app/src/ohos_application.cpp @@ -118,13 +118,15 @@ void OHOSApplication::DumpApplication() */ void OHOSApplication::SetAbilityRecordMgr(const std::shared_ptr &abilityRecordMgr) { + APP_LOGI("OHOSApplication::SetAbilityRecordMgr. Start"); if (abilityRecordMgr == nullptr) { APP_LOGE("ContextDeal::SetAbilityRecordMgr failed, abilityRecordMgr is nullptr"); return; } abilityRecordMgr_ = abilityRecordMgr; + APP_LOGI("OHOSApplication::SetAbilityRecordMgr. End"); } - + /** * * Register AbilityLifecycleCallbacks with OHOSApplication 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/kits/appkit/native/test/unittest/application_impl_test.cpp b/kits/appkit/native/test/unittest/application_impl_test.cpp index 0e3729c8b96f6bfb680eb92cd44c44ce878dcfcb..7896d1ec62ab39996444e89ea38f71bc0cfeaaf6 100644 --- a/kits/appkit/native/test/unittest/application_impl_test.cpp +++ b/kits/appkit/native/test/unittest/application_impl_test.cpp @@ -26,13 +26,11 @@ using namespace OHOS::AppExecFwk; class ApplicationImplTest : public testing::Test { public: - ApplicationImplTest() : applicationImpl_(nullptr) + ApplicationImplTest() {} ~ApplicationImplTest() - { - applicationImpl_ = nullptr; - } - ApplicationImpl *applicationImpl_ = nullptr; + {} + std::shared_ptr applicationImpl_ = nullptr; static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); @@ -47,14 +45,11 @@ void ApplicationImplTest::TearDownTestCase(void) void ApplicationImplTest::SetUp(void) { - applicationImpl_ = new (std::nothrow) ApplicationImpl(); + applicationImpl_ = std::make_shared(); } void ApplicationImplTest::TearDown(void) -{ - delete applicationImpl_; - applicationImpl_ = nullptr; -} +{} /** * @tc.number: AppExecFwk_ApplicationImpl_PerformAppReady_0100 diff --git a/kits/appkit/native/test/unittest/application_test.cpp b/kits/appkit/native/test/unittest/application_test.cpp index 08ea6c739764af10fb629e52127af78d47831657..1c476997376b357b051d7d3721f41f3cf925d598 100644 --- a/kits/appkit/native/test/unittest/application_test.cpp +++ b/kits/appkit/native/test/unittest/application_test.cpp @@ -28,13 +28,11 @@ namespace OHOS { namespace AppExecFwk { class ApplicationTest : public testing::Test { public: - ApplicationTest() : ApplicationTest_(nullptr) + ApplicationTest() {} ~ApplicationTest() - { - ApplicationTest_ = nullptr; - } - OHOSApplication *ApplicationTest_ = nullptr; + {} + std::shared_ptr ApplicationTest_ = nullptr; static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); @@ -49,14 +47,11 @@ void ApplicationTest::TearDownTestCase(void) void ApplicationTest::SetUp(void) { - ApplicationTest_ = new (std::nothrow) OHOSApplication(); + ApplicationTest_ = std::make_shared(); } void ApplicationTest::TearDown(void) -{ - delete ApplicationTest_; - ApplicationTest_ = nullptr; -} +{} /** * @tc.number: AppExecFwk_Application_RegisterAbilityLifecycleCallbacks_0100 diff --git a/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp b/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp index aa6da460fe1f77151ff50e7598fddc865bc64d4c..f9bf13577ecc746e996139e84444d12d95b1ab51 100644 --- a/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp +++ b/kits/appkit/native/test/unittest/context_deal_interface1_test.cpp @@ -131,7 +131,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetTheme_0100, Functio resourceManager->SetThemeById(testValue, testList); contextDeal->initResourceManager(resourceManager); contextDeal->SetTheme(testValue); - // EXPECT_EQ(testValue, contextDeal->GetHapModuleInfo()->themeId); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0100 end"; } @@ -146,7 +145,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_SetTheme_0200, Functio int testValue = 1; std::shared_ptr contextDeal = std::make_shared(); contextDeal->SetTheme(testValue); - // EXPECT_NE(testValue, contextDeal->GetHapModuleInfo()->themeId); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_SetTheme_0200 end"; } @@ -249,7 +247,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetTheme_0100, Functio contextDeal->initResourceManager(resourceManager); std::map retVal = contextDeal->GetTheme(); - // EXPECT_TRUE((retVal == testList)); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetTheme_0100 end"; } @@ -279,12 +276,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetString_ById_0100, F HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100 start"; - // std::shared_ptr resourceManager(Global::Resource::CreateResourceManager2()); - // std::shared_ptr contextDeal = std::make_shared(); - // int testCount = 0; - // std::string testByName = ""; - // std::string retVal = contextDeal->GetString(testCount, testByName); - // EXPECT_TRUE(false); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetString_ByIdAndFormat_0100 end"; } @@ -410,10 +401,6 @@ HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetColor_0200, Functio HWTEST_F(ContextDealInterfaceTest, AppExecFwk_ContextDeal_GetThemeId_0100, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetThemeId_0100 start"; - // std::shared_ptr contextDeal = std::make_shared(); - // const int testValue = 1; - // contextDeal->GetHapModuleInfo()->themeId = testValue; - // EXPECT_EQ(testValue, contextDeal->GetThemeId()); GTEST_LOG_(INFO) << "AppExecFwk_ContextDeal_GetThemeId_0100 end"; } diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp index d1ee4a6c993d50b4eeb93c3dbf3e2ba6b6be0910..3284e86ac4b49e735ac06e77aaf2d6052736e9d8 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_first.cpp @@ -29,6 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; +const int TestProcessInfo = 9999; +const int USleepTime = 200; class AppkitNativeModuleTestFirst : public testing::Test { public: @@ -70,14 +72,14 @@ void AppkitNativeModuleTestFirst::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestFirst TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -93,12 +95,12 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_Start_0100, Function | MediumTest | Le GTEST_LOG_(INFO) << "App_Start_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); - usleep(200); + usleep(USleepTime); GTEST_LOG_(INFO) << "App_Start_0100 end"; } @@ -112,7 +114,7 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_Start_0200, Function | MediumTest | Le { GTEST_LOG_(INFO) << "App_Start_0200 start"; runner_->Run(); - usleep(200); + usleep(USleepTime); EXPECT_EQ(false, mockAppMgr->IsAttached()); runner_->Stop(); GTEST_LOG_(INFO) << "App_Start_0200 end"; @@ -132,30 +134,30 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0100, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -174,11 +176,11 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0200, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -197,11 +199,11 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0300, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -220,11 +222,11 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0400, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0400 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -243,22 +245,22 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0500, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0500 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -277,22 +279,22 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0600, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0600 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -311,22 +313,22 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0700, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0700 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -345,26 +347,26 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0800, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0800 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -383,26 +385,26 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_0900, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_0900 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -421,26 +423,26 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1000, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1000 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -459,30 +461,30 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1100, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -501,30 +503,30 @@ HWTEST_F(AppkitNativeModuleTestFirst, App_ApplicationLifeCycle_1200, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(200); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(200); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(200); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp index d41d3d77a5e02ab1fce94aa31ba251f9d5434f5e..5a14d27b09bee5750feb60d1f47751edc5d3352d 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_fourth.cpp @@ -29,7 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; - +const int TestProcessInfo = 9999; +const int USleepTime = 50; class AppkitNativeModuleTestThird : public testing::Test { public: AppkitNativeModuleTestThird() : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) @@ -70,14 +71,14 @@ void AppkitNativeModuleTestThird::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -96,28 +97,28 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0100, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleLaunchAbility(abilityinf, token); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleCleanAbility(token); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -138,12 +139,12 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0200, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleCleanAbility(token); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -164,23 +165,23 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0300, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleCleanAbility(token); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -201,28 +202,28 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0400, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0400 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleLaunchAbility(abilityinf, token); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleCleanAbility(nullptr); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -243,28 +244,28 @@ HWTEST_F(AppkitNativeModuleTestThird, App_CleanAbility_0500, Function | MediumTe GTEST_LOG_(INFO) << "App_CleanAbility_0500 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleLaunchAbility(abilityinf, token); - usleep(50); + usleep(USleepTime); sptr tokenOhter = new (std::nothrow) MockAbilityToken(); mockAppMgr->ScheduleCleanAbility(tokenOhter); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -284,7 +285,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_ElementsCallbacks_0100, Function | Med GTEST_LOG_(INFO) << "App_ElementsCallbacks_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; @@ -295,20 +296,20 @@ HWTEST_F(AppkitNativeModuleTestThird, App_ElementsCallbacks_0100, Function | Med lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleShrinkMemory(10); - usleep(50); + usleep(USleepTime); OHOS::AppExecFwk::Configuration config("testConfig"); mockAppMgr->ScheduleConfigurationUpdated(config); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -332,7 +333,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_AbilityLifecycleCallbacks_0100, Functi GTEST_LOG_(INFO) << "App_AbilityLifecycleCallbacks_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; @@ -343,7 +344,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_AbilityLifecycleCallbacks_0100, Functi lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp index e42c61c8e6cf95ddfd49920f5c5ea8bc44304592..65edcd5018d528e2ee579b99356696d4e25f496d 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_second.cpp @@ -29,7 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; - +const int TestProcessInfo = 9999; +const int USleepTime = 50; class AppkitNativeModuleTestSecond : public testing::Test { public: AppkitNativeModuleTestSecond() @@ -71,14 +72,14 @@ void AppkitNativeModuleTestSecond::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestSecond TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -95,30 +96,30 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1300, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleForegroundApplication(); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleBackgroundApplication(); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -137,18 +138,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1400, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1400 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -167,18 +168,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_ApplicationLifeCycle_1500, Function | GTEST_LOG_(INFO) << "App_ApplicationLifeCycle_1500 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); @@ -198,18 +199,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0100, Function | MediumT GTEST_LOG_(INFO) << "App_LaunchAblity_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); @@ -233,7 +234,7 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0200, Function | MediumT GTEST_LOG_(INFO) << "App_LaunchAblity_0200 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; sptr token = new (std::nothrow) MockAbilityToken(); @@ -258,18 +259,18 @@ HWTEST_F(AppkitNativeModuleTestSecond, App_LaunchAblity_0300, Function | MediumT GTEST_LOG_(INFO) << "App_LaunchAblity_0300 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); AbilityInfo abilityinf; mockAppMgr->ScheduleLaunchAbility(abilityinf, nullptr); diff --git a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp index 4e21ad58c4bd60cd1ee2c9d840a178830865d8ad..a6d6b603469827de49cc2f9f10fea9ab29bad1ea 100644 --- a/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp +++ b/kits/appkit/test/moduletest/appexecfwk_appkit_native_app_module_test_third.cpp @@ -29,7 +29,8 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; using namespace OHOS; using namespace OHOS::AAFwk; - +const int TestProcessInfo = 9999; +const int USleepTime = 50; class AppkitNativeModuleTestThird : public testing::Test { public: AppkitNativeModuleTestThird() : AppMgrObject_(nullptr), mockAppMgr(nullptr), mockHandler_(nullptr), runner_(nullptr) @@ -70,14 +71,14 @@ void AppkitNativeModuleTestThird::TearDown(void) GTEST_LOG_(INFO) << "AppkitNativeModuleTestThird TearDown"; AppLaunchData lanchdate; ApplicationInfo appinf; - ProcessInfo processinf("TestProcess", 9999); + ProcessInfo processinf("TestProcess", TestProcessInfo); appinf.name = "MockTestApplication"; appinf.moduleSourceDirs.push_back("/hos/lib/libabilitydemo_native.z.so"); lanchdate.SetApplicationInfo(appinf); lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); mockAppMgr->ScheduleTerminateApplication(); } @@ -95,7 +96,7 @@ HWTEST_F(AppkitNativeModuleTestThird, App_Context_ApplicationContext_0100, Funct GTEST_LOG_(INFO) << "App_Context_ApplicationContext_0100 start"; OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility(APP_MGR_SERVICE_ID, AppMgrObject_); runner_->Run(); - usleep(50); + usleep(USleepTime); AppLaunchData lanchdate; ApplicationInfo appinf; @@ -110,12 +111,12 @@ HWTEST_F(AppkitNativeModuleTestThird, App_Context_ApplicationContext_0100, Funct lanchdate.SetProcessInfo(processinf); mockAppMgr->ScheduleLaunchApplication(lanchdate); - usleep(50); + usleep(USleepTime); runner_->Stop(); OHOS::DelayedSingleton::GetInstance()->UnregisterSystemAbility(APP_MGR_SERVICE_ID); - usleep(50); + usleep(USleepTime); GTEST_LOG_(INFO) << "App_Context_ApplicationContext_0100 end"; } } // namespace AppExecFwk diff --git a/libs/libeventhandler/src/event_queue.cpp b/libs/libeventhandler/src/event_queue.cpp index dc1fc3d957a1dab6896a3ecb5de80c15a7eadd2f..c426aef047aca6c65b40d7309eba253fe577d472 100644 --- a/libs/libeventhandler/src/event_queue.cpp +++ b/libs/libeventhandler/src/event_queue.cpp @@ -48,7 +48,7 @@ void RemoveFileDescriptorListenerLocked(std::mapsecond)) { ioWaiter->RemoveFileDescriptor(it->first); it = listeners.erase(it); diff --git a/libs/libeventhandler/src/event_runner.cpp b/libs/libeventhandler/src/event_runner.cpp index 1c635df8ca3e529745924f9c45c686c2c58cb7f1..10cb96c76a397a93f11675c2b8f799e92a6cb3df 100644 --- a/libs/libeventhandler/src/event_runner.cpp +++ b/libs/libeventhandler/src/event_runner.cpp @@ -248,8 +248,8 @@ private: static Avatar avatar_; }; -ThreadCollector::ThreadCollector() : - collectorLock_(), condition_(), reclaims_(), depositMap_(), threadLock_(), thread_(nullptr) +ThreadCollector::ThreadCollector() + : collectorLock_(), condition_(), reclaims_(), depositMap_(), threadLock_(), thread_(nullptr) { // Thread collector is created, so enable avatar. avatarEnabled_ = true; @@ -372,8 +372,8 @@ private: }; } // unnamed namespace -EventInnerRunner::EventInnerRunner(const std::shared_ptr &runner) : - queue_(nullptr), owner_(runner), logger_(nullptr), threadName_(""), threadId_() +EventInnerRunner::EventInnerRunner(const std::shared_ptr &runner) + : queue_(nullptr), owner_(runner), logger_(nullptr), threadName_(""), threadId_() {} std::shared_ptr EventInnerRunner::GetCurrentEventRunner() diff --git a/libs/libeventhandler/src/thread_local_data.h b/libs/libeventhandler/src/thread_local_data.h index 1fd69b8d1f16561c9e8cf4f3fe71ed61b9e239fd..1b2655fdcca0fb8cd33fed3329e7c88e0c1fc3eb 100644 --- a/libs/libeventhandler/src/thread_local_data.h +++ b/libs/libeventhandler/src/thread_local_data.h @@ -27,7 +27,7 @@ namespace AppExecFwk { /* * Tool class, used to save thread local data. */ -template +template class ThreadLocalData { public: ThreadLocalData() = default; 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..3d8f773fff1f9681dca3780ece567085535fe8aa 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,15 +205,15 @@ 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); auto handler = std::make_shared(myRunner); auto inResult = handler->AddFileDescriptorListener(fds[0], FILE_DESCRIPTOR_INPUT_EVENT, listener); - ASSERT_EQ(inResult, ERR_OK); + EXPECT_EQ(inResult, ERR_OK); auto outResult = handler->AddFileDescriptorListener(fds[1], FILE_DESCRIPTOR_OUTPUT_EVENT, listener); - ASSERT_EQ(outResult, ERR_OK); + EXPECT_EQ(outResult, ERR_OK); int64_t delayTime = 20000; int64_t param = 0; 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..51803d21fd41da4065c86f4944447c1237268871 100644 --- a/services/appmgr/include/ability_running_record.h +++ b/services/appmgr/include/ability_running_record.h @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { - class AbilityRunningRecord { public: AbilityRunningRecord(const std::shared_ptr &info, const sptr &token); @@ -154,13 +153,12 @@ 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_; sptr preToken_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_ABILITY_RUNNING_RECORD_H diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h index 3cd7b66e42adc0fd28e75e55aebffbf4b5228a1e..a384d99f36a2d7b179e7cfcedb0c55b0c12f1efb 100644 --- a/services/appmgr/include/ams_mgr_scheduler.h +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -34,7 +34,6 @@ namespace OHOS { namespace AppExecFwk { - class AmsMgrScheduler : public AmsMgrStub { public: AmsMgrScheduler( @@ -144,7 +143,6 @@ private: DISALLOW_COPY_AND_MOVE(AmsMgrScheduler); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_AMS_MGR_SCHEDULER_H diff --git a/services/appmgr/include/app_death_recipient.h b/services/appmgr/include/app_death_recipient.h index b7ee4974f69027e8012752a6222afba98d25f7f9..39179e0b3a0e9864b882dc210820b8634f83b888 100644 --- a/services/appmgr/include/app_death_recipient.h +++ b/services/appmgr/include/app_death_recipient.h @@ -22,7 +22,6 @@ namespace OHOS { namespace AppExecFwk { - class AppMgrServiceInner; class AppDeathRecipient : public IRemoteObject::DeathRecipient { @@ -47,7 +46,6 @@ private: std::weak_ptr handler_; std::weak_ptr appMgrServiceInner_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_DEATH_RECIPIENT_H diff --git a/services/appmgr/include/app_lifecycle_deal.h b/services/appmgr/include/app_lifecycle_deal.h index 351224881ee93d2e777f1be0ad5e6b8d7fe26f42..406f6b0fa7ae5c6295bffb92c5e9c310cfc56de8 100644 --- a/services/appmgr/include/app_lifecycle_deal.h +++ b/services/appmgr/include/app_lifecycle_deal.h @@ -21,11 +21,8 @@ #include "ability_running_record.h" namespace OHOS { - namespace AppExecFwk { - class AppLifeCycleDeal { - public: AppLifeCycleDeal(); virtual ~AppLifeCycleDeal(); @@ -125,7 +122,6 @@ public: private: sptr appThread_; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/app_mgr_service.h b/services/appmgr/include/app_mgr_service.h index 60bc23a715c86253cf5a94204cf420c29417df70..8a67ec6bfa792d44d30d46d3cff2396b16d19ae9 100644 --- a/services/appmgr/include/app_mgr_service.h +++ b/services/appmgr/include/app_mgr_service.h @@ -39,7 +39,6 @@ namespace OHOS { namespace AppExecFwk { - enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; struct AppMgrServiceState { @@ -232,7 +231,6 @@ private: DISALLOW_COPY_AND_MOVE(AppMgrService); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_H diff --git a/services/appmgr/include/app_mgr_service_event_handler.h b/services/appmgr/include/app_mgr_service_event_handler.h index e94ef2dfce9d84dcde88195c22ec9f02179b72cc..4a7fe990b2f239d7d9d8efe861b98bb748041465 100644 --- a/services/appmgr/include/app_mgr_service_event_handler.h +++ b/services/appmgr/include/app_mgr_service_event_handler.h @@ -20,7 +20,6 @@ namespace OHOS { namespace AppExecFwk { - class AppMgrServiceInner; class AMSEventHandler : public EventHandler { @@ -38,7 +37,6 @@ public: private: std::weak_ptr appMgr_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_EVENT_HANDLER_H diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 18d6d27549b65e9854328b4a9bda47e15e472368..9bda97a256bdc62cc2102f83c747565bdad89f2c 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -46,7 +46,6 @@ namespace OHOS { namespace AppExecFwk { - using OHOS::AAFwk::Want; class AppMgrServiceInner : public std::enable_shared_from_this { @@ -450,6 +449,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 +520,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). * @@ -640,7 +639,6 @@ private: std::shared_ptr eventHandler_; std::mutex serviceLock_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_MGR_SERVICE_INNER_H diff --git a/services/appmgr/include/app_process_manager.h b/services/appmgr/include/app_process_manager.h index ca7494017c163810c6dc1913c71c190067cb0120..9e92a62df7c312875048d4eacd342a75601cbd5b 100644 --- a/services/appmgr/include/app_process_manager.h +++ b/services/appmgr/include/app_process_manager.h @@ -24,11 +24,8 @@ #include "app_task_info.h" namespace OHOS { - namespace AppExecFwk { - class AppProcessManager { - public: AppProcessManager(); virtual ~AppProcessManager(); @@ -110,7 +107,6 @@ public: private: std::list> recentAppList_; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/app_running_manager.h b/services/appmgr/include/app_running_manager.h index 3f5c4a18f8d83dd0f39dd95865bacb88db13bed9..4299d82896dc1582f3a02aad776f2b9512e707d1 100644 --- a/services/appmgr/include/app_running_manager.h +++ b/services/appmgr/include/app_running_manager.h @@ -28,11 +28,8 @@ #include "record_query_result.h" namespace OHOS { - namespace AppExecFwk { - class AppRunningManager { - public: AppRunningManager(); virtual ~AppRunningManager(); @@ -126,6 +123,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); @@ -133,7 +132,6 @@ private: std::map> appRunningRecordMap_; std::recursive_mutex lock_; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index bbc2cb3f7242a37ca117d416d35ab6eac3d4ab7e..501bb4b6469f0251e43004675a89946ad671ada2 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -36,11 +36,10 @@ namespace OHOS { 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 +272,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 +408,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_; @@ -415,7 +417,6 @@ private: std::shared_ptr eventHandler_; bool isTerminating = false; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_RUNNING_RECORD_H diff --git a/services/appmgr/include/app_spawn_client.h b/services/appmgr/include/app_spawn_client.h index e82adfbbe8ad2b34e7d51e5770aaa373c9f6a29f..862e80345572bd60bf1a0838b9bd4063119a2a53 100644 --- a/services/appmgr/include/app_spawn_client.h +++ b/services/appmgr/include/app_spawn_client.h @@ -22,7 +22,6 @@ namespace OHOS { namespace AppExecFwk { - enum class SpawnConnectionState { STATE_NOT_CONNECT, STATE_CONNECTED, STATE_CONNECT_FAILED }; class AppSpawnClient { @@ -83,7 +82,6 @@ private: std::shared_ptr socket_; SpawnConnectionState state_ = SpawnConnectionState::STATE_NOT_CONNECT; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_CLIENT_H diff --git a/services/appmgr/include/app_spawn_msg_wrapper.h b/services/appmgr/include/app_spawn_msg_wrapper.h index 558e97a3aa3281b27d36eeefdab7a256aa77b97b..8abc4abd363f89ccbf0585168e7e30601bcf8687 100644 --- a/services/appmgr/include/app_spawn_msg_wrapper.h +++ b/services/appmgr/include/app_spawn_msg_wrapper.h @@ -25,7 +25,6 @@ namespace OHOS { namespace AppExecFwk { - struct AppSpawnStartMsg { int32_t uid; int32_t gid; @@ -116,7 +115,6 @@ private: // because AppSpawnMsg's size is uncertain, so should use raw pointer. AppSpawnMsg *msg_ = nullptr; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_MSG_WRAPPER_H diff --git a/services/appmgr/include/app_spawn_socket.h b/services/appmgr/include/app_spawn_socket.h index 7ecd6925162590ce444ed22b377d68d77ceab102..ef133c455abd192461b499a405cbd054df8b95fa 100644 --- a/services/appmgr/include/app_spawn_socket.h +++ b/services/appmgr/include/app_spawn_socket.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class AppSpawnSocket { public: /** @@ -78,7 +77,6 @@ public: private: std::shared_ptr clientSocket_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_APP_SPAWN_SOCKET_H \ No newline at end of file diff --git a/services/appmgr/include/cgroup_manager.h b/services/appmgr/include/cgroup_manager.h index 71162d501cc97ccb6640e6c7d5bd6fecf270a85c..5cfbab241047697648a8c2e37b280e8af5813869 100644 --- a/services/appmgr/include/cgroup_manager.h +++ b/services/appmgr/include/cgroup_manager.h @@ -28,7 +28,6 @@ namespace OHOS { namespace AppExecFwk { - class CgroupManager : public FileDescriptorListener, public std::enable_shared_from_this { DECLARE_DELAYED_SINGLETON(CgroupManager) @@ -67,6 +66,7 @@ public: public: virtual bool Init(); + virtual bool InitCheck(); virtual bool IsInited() const; virtual bool SetThreadSchedPolicy(int tid, SchedPolicy schedPolicy); virtual bool SetProcessSchedPolicy(int pid, SchedPolicy schedPolicy); @@ -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/lmks/lmks_server.h b/services/appmgr/include/lmks/lmks_server.h index 34744999fdac1d4bf9ea5b2e6ef61da17add37c6..86e56cffd30ee8530b6c33946687e4e94e27d8fb 100644 --- a/services/appmgr/include/lmks/lmks_server.h +++ b/services/appmgr/include/lmks/lmks_server.h @@ -23,11 +23,10 @@ namespace OHOS { namespace LMKS { +constexpr uint32_t MAX_LMKS_TARGETS = 6; // max number of lmks command targets +constexpr uint32_t MAX_LMKS_TARGETS_SIZE = sizeof(int) * (MAX_LMKS_TARGETS * 2 + 1); // max packet length -constexpr uint32_t MAX_LMKS_TARGETS = 6; // max number of lmks command targets -constexpr uint32_t MAX_LMKS_TARGETS_SIZE = sizeof(int) * (MAX_LMKS_TARGETS * 2 + 1); // max packet length - -using LMKS_PACKET=int[MAX_LMKS_TARGETS_SIZE / sizeof(int)]; +using LMKS_PACKET = int[MAX_LMKS_TARGETS_SIZE / sizeof(int)]; class LmksServer { public: diff --git a/services/appmgr/include/lmks/lmks_utils.h b/services/appmgr/include/lmks/lmks_utils.h index f803bf6ffe9e91c2852840d3960633231cb2cfec..bda20db18af30461929a591a7c6c65aad4bd4c49 100644 --- a/services/appmgr/include/lmks/lmks_utils.h +++ b/services/appmgr/include/lmks/lmks_utils.h @@ -21,13 +21,13 @@ namespace OHOS { namespace LMKS { - class LmksUtils { public: LmksUtils(); virtual ~LmksUtils(); int RemoveProcess(pid_t pid); + private: std::string GetProcName(pid_t pid); int GetProcSize(pid_t pid); diff --git a/services/appmgr/include/lmks_client.h b/services/appmgr/include/lmks_client.h index c2ece8d0992ac5a29bf6e48e9a5f2cc728868d45..63b8934e3c74d1a0cf02487ce3246f50a8e2bf21 100644 --- a/services/appmgr/include/lmks_client.h +++ b/services/appmgr/include/lmks_client.h @@ -28,7 +28,6 @@ namespace OHOS { namespace AppExecFwk { - union LmksClientMsg { int32_t result = -1; int8_t resultBuf[sizeof(int32_t)]; @@ -57,7 +56,6 @@ private: private: int socket_; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/process_optimizer.h b/services/appmgr/include/process_optimizer.h index 8e7b2f8a208df6ca937d44b3100f4fe49f17d3c0..10b4028bcff4cc9ac3228b8d814f66f98fcc183d 100644 --- a/services/appmgr/include/process_optimizer.h +++ b/services/appmgr/include/process_optimizer.h @@ -31,7 +31,6 @@ namespace OHOS { namespace AppExecFwk { - class ProcessOptimizer : public NoCopyable { public: using EventHandlerPtr = std::shared_ptr; @@ -40,7 +39,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); @@ -76,6 +76,7 @@ protected: private: bool UpdateAppOomAdj(const AppPtr &app); + bool GetAppOomAdj(const AppPtr &app,ApplicationState state,int &oomAdj,int &oomAdjMax); bool UpdateAppSchedPolicy(const AppPtr &app); void StartAppSuspendTimer(const AppPtr &app); void StopAppSuspendTimer(const AppPtr &app); diff --git a/services/appmgr/include/process_optimizer_uba.h b/services/appmgr/include/process_optimizer_uba.h index 45752b22221ddc591807d63d316542363ad826df..89c0440afd1ef1ec8e6eeaa633fa76c2e438cbca 100644 --- a/services/appmgr/include/process_optimizer_uba.h +++ b/services/appmgr/include/process_optimizer_uba.h @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { - // UBA short for User Behavior Analysis using UbaService = int; using UbaServicePtr = std::shared_ptr; @@ -148,7 +147,7 @@ private: std::variant; - template + template void RecordAbilityAction(ARGS... args) { abilityActionCache_[abilityActionCount_++].emplace(args...); @@ -158,6 +157,11 @@ private: } void CommitAbilityActions(); + void CommitStartAbilityAction(const StartAbilityAction& action, size_t index); + void CommitConnectAbilityAction(const ConnectAbilityAction& action, size_t index); + void CommitDisconnectAbilityAction(const DisconnectAbilityAction& action, size_t index); + void CommitChangedAbilityStateAction(const ChangeAbilityStateAction& action, size_t index); + void CommitRemoveAbilityAction(const RemoveAbilityAction& action, size_t index); UbaServicePtr GetUbaService(); private: diff --git a/services/appmgr/include/record_query_result.h b/services/appmgr/include/record_query_result.h index c0a4a8b2a88cbe6fc9d416eb0efebc67522e69a7..539d7e50e956b5e0ce0ebb6f929dfbf3db0a21a5 100644 --- a/services/appmgr/include/record_query_result.h +++ b/services/appmgr/include/record_query_result.h @@ -18,7 +18,6 @@ namespace OHOS { namespace AppExecFwk { - struct RecordQueryResult { void Reset() { @@ -34,7 +33,6 @@ struct RecordQueryResult { bool abilityExists = false; ErrCode error = ERR_OK; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/remote_client_manager.h b/services/appmgr/include/remote_client_manager.h index 1f74b8e27be12a877c8563f8e18e3929ef611184..35656ea55639e172bd943573e30a873e93afac95 100644 --- a/services/appmgr/include/remote_client_manager.h +++ b/services/appmgr/include/remote_client_manager.h @@ -23,9 +23,7 @@ #include "bundlemgr/bundle_mgr_interface.h" namespace OHOS { - namespace AppExecFwk { - class RemoteClientManager { public: RemoteClientManager(); @@ -63,7 +61,6 @@ private: std::shared_ptr appSpawnClient_; sptr bundleManager_; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/start_via_asan.h b/services/appmgr/include/start_via_asan.h index a2a1d3cfe0d66a3e168fb10b5a9906d1909e7533..599033add477cebd6a82837c731e9399a7fc6f79 100644 --- a/services/appmgr/include/start_via_asan.h +++ b/services/appmgr/include/start_via_asan.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class StartViaAsan { DECLARE_DELAYED_SINGLETON(StartViaAsan); @@ -32,7 +31,6 @@ public: bool IsAsanVersion(const std::string &appName) const; void GetAsanStartMsg(AppSpawnStartMsg &startMsg) const; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_INCLUDE_START_VIA_ASAN_H \ No newline at end of file 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/ability_running_record.cpp b/services/appmgr/src/ability_running_record.cpp index 0408b09d2ac962a518d25b863167a4d0e2758e47..ae38b7a31bd4aac8f42428977b84885bf44b3d7a 100644 --- a/services/appmgr/src/ability_running_record.cpp +++ b/services/appmgr/src/ability_running_record.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - AbilityRunningRecord::AbilityRunningRecord(const std::shared_ptr &info, const sptr &token) : info_(info), token_(token) {} @@ -111,6 +110,5 @@ int64_t AbilityRunningRecord::GetEventId() const { return eventId_; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 3dd9fc8e5d2f3cc7fbe1ed1fb2eb77fe045999e3..2dba594b6178bddacc8248fd3e90bf0beb5d7ebf 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -26,11 +26,8 @@ #include "perf_profile.h" namespace OHOS { - namespace AppExecFwk { - namespace { - const std::string TASK_LOAD_ABILITY = "LoadAbilityTask"; const std::string TASK_TERMINATE_ABILITY = "TerminateAbilityTask"; const std::string TASK_UPDATE_ABILITY_STATE = "UpdateAbilityStateTask"; @@ -63,7 +60,7 @@ void AmsMgrScheduler::LoadAbility(const sptr &token, const sptr loadAbilityFunc = + std::function loadAbilityFunc = std::bind(&AppMgrServiceInner::LoadAbility, amsMgrServiceInner_, token, preToken, abilityInfo, appInfo); amsHandler_->PostTask(loadAbilityFunc, TASK_LOAD_ABILITY); @@ -74,7 +71,7 @@ void AmsMgrScheduler::UpdateAbilityState(const sptr &token, const if (!IsReady()) { return; } - std::function updateAbilityStateFunc = + std::function updateAbilityStateFunc = std::bind(&AppMgrServiceInner::UpdateAbilityState, amsMgrServiceInner_, token, state); amsHandler_->PostTask(updateAbilityStateFunc, TASK_UPDATE_ABILITY_STATE); } @@ -84,7 +81,7 @@ void AmsMgrScheduler::TerminateAbility(const sptr &token) if (!IsReady()) { return; } - std::function terminateAbilityFunc = + std::function terminateAbilityFunc = std::bind(&AppMgrServiceInner::TerminateAbility, amsMgrServiceInner_, token); amsHandler_->PostTask(terminateAbilityFunc, TASK_TERMINATE_ABILITY); } @@ -94,7 +91,7 @@ void AmsMgrScheduler::RegisterAppStateCallback(const sptr &ca if (!IsReady()) { return; } - std::function registerAppStateCallbackFunc = + std::function registerAppStateCallbackFunc = std::bind(&AppMgrServiceInner::RegisterAppStateCallback, amsMgrServiceInner_, callback); amsHandler_->PostTask(registerAppStateCallbackFunc, TASK_REGISTER_APP_STATE_CALLBACK); } @@ -104,7 +101,7 @@ void AmsMgrScheduler::Reset() if (!IsReady()) { return; } - std::function resetFunc = std::bind(&AppMgrServiceInner::StopAllProcess, amsMgrServiceInner_); + std::function resetFunc = std::bind(&AppMgrServiceInner::StopAllProcess, amsMgrServiceInner_); amsHandler_->PostTask(resetFunc, TASK_STOP_ALL_PROCESS); } @@ -114,7 +111,7 @@ void AmsMgrScheduler::AbilityBehaviorAnalysis(const sptr &token, if (!IsReady()) { return; } - std::function abilityBehaviorAnalysisFunc = std::bind(&AppMgrServiceInner::AbilityBehaviorAnalysis, + std::function abilityBehaviorAnalysisFunc = std::bind(&AppMgrServiceInner::AbilityBehaviorAnalysis, amsMgrServiceInner_, token, preToken, @@ -129,7 +126,7 @@ void AmsMgrScheduler::KillProcessByAbilityToken(const sptr &token if (!IsReady()) { return; } - std::function killProcessByAbilityTokenFunc = + std::function killProcessByAbilityTokenFunc = std::bind(&AppMgrServiceInner::KillProcessByAbilityToken, amsMgrServiceInner_, token); amsHandler_->PostTask(killProcessByAbilityTokenFunc, TASK_KILL_PROCESS_BY_ABILITYTOKEN); } diff --git a/services/appmgr/src/app_death_recipient.cpp b/services/appmgr/src/app_death_recipient.cpp index c9181e1d40e1af583ceb5eee9745369e1866cde7..f094ad812e022910fcff4de541a5aada7c72de7d 100644 --- a/services/appmgr/src/app_death_recipient.cpp +++ b/services/appmgr/src/app_death_recipient.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { namespace { - const std::string TASK_ON_REMOTE_DIED = "OnRemoteDiedTask"; } @@ -43,7 +42,7 @@ void AppDeathRecipient::OnRemoteDied(const wptr &remote) return; } - std::function onRemoteDiedFunc = std::bind(&AppMgrServiceInner::OnRemoteDied, serviceInner, remote); + std::function onRemoteDiedFunc = std::bind(&AppMgrServiceInner::OnRemoteDied, serviceInner, remote); handler->PostTask(onRemoteDiedFunc, TASK_ON_REMOTE_DIED); } @@ -56,6 +55,5 @@ void AppDeathRecipient::SetAppMgrServiceInner(const std::shared_ptr AppLifeCycleDeal::GetApplicationClient() const { return appThread_; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp index 395c2cb5913ea6a53398ced8539737d4835c46bc..7869d78bde6aa8bc15c83fedf1022a1c8fc75cf7 100644 --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -29,7 +29,6 @@ namespace OHOS { namespace AppExecFwk { namespace { - const std::string TASK_ATTACH_APPLICATION = "AttachApplicationTask"; const std::string TASK_APPLICATION_FOREGROUNDED = "ApplicationForegroundedTask"; const std::string TASK_APPLICATION_BACKGROUNDED = "ApplicationBackgroundedTask"; @@ -37,7 +36,6 @@ const std::string TASK_APPLICATION_TERMINATED = "ApplicationTerminatedTask"; const std::string TASK_ABILITY_CLEANED = "AbilityCleanedTask"; const std::string TASK_ADD_APP_DEATH_RECIPIENT = "AddAppRecipientTask"; const std::string TASK_CLEAR_UP_APPLICATION_DATA = "ClearUpApplicationDataTask"; - } // namespace REGISTER_SYSTEM_ABILITY_BY_ID(AppMgrService, APP_MGR_SERVICE_ID, true); @@ -160,7 +158,7 @@ void AppMgrService::AttachApplication(const sptr &app) pid_t pid = IPCSkeleton::GetCallingPid(); AddAppDeathRecipient(pid); - std::function attachApplicationFunc = + std::function attachApplicationFunc = std::bind(&AppMgrServiceInner::AttachApplication, appMgrServiceInner_, pid, iface_cast(app)); handler_->PostTask(attachApplicationFunc, TASK_ATTACH_APPLICATION); } @@ -170,7 +168,7 @@ void AppMgrService::ApplicationForegrounded(const int32_t recordId) if (!IsReady()) { return; } - std::function applicationForegroundedFunc = + std::function applicationForegroundedFunc = std::bind(&AppMgrServiceInner::ApplicationForegrounded, appMgrServiceInner_, recordId); handler_->PostTask(applicationForegroundedFunc, TASK_APPLICATION_FOREGROUNDED); } @@ -180,7 +178,7 @@ void AppMgrService::ApplicationBackgrounded(const int32_t recordId) if (!IsReady()) { return; } - std::function applicationBackgroundedFunc = + std::function applicationBackgroundedFunc = std::bind(&AppMgrServiceInner::ApplicationBackgrounded, appMgrServiceInner_, recordId); handler_->PostTask(applicationBackgroundedFunc, TASK_APPLICATION_BACKGROUNDED); } @@ -190,7 +188,7 @@ void AppMgrService::ApplicationTerminated(const int32_t recordId) if (!IsReady()) { return; } - std::function applicationTerminatedFunc = + std::function applicationTerminatedFunc = std::bind(&AppMgrServiceInner::ApplicationTerminated, appMgrServiceInner_, recordId); handler_->PostTask(applicationTerminatedFunc, TASK_APPLICATION_TERMINATED); } @@ -200,7 +198,7 @@ void AppMgrService::AbilityCleaned(const sptr &token) if (!IsReady()) { return; } - std::function abilityCleanedFunc = + std::function abilityCleanedFunc = std::bind(&AppMgrServiceInner::AbilityTerminated, appMgrServiceInner_, token); handler_->PostTask(abilityCleanedFunc, TASK_ABILITY_CLEANED); } @@ -226,7 +224,7 @@ void AppMgrService::AddAppDeathRecipient(const pid_t pid) const sptr appDeathRecipient = new AppDeathRecipient(); appDeathRecipient->SetEventHandler(handler_); appDeathRecipient->SetAppMgrServiceInner(appMgrServiceInner_); - std::function addAppRecipientFunc = + std::function addAppRecipientFunc = std::bind(&AppMgrServiceInner::AddAppDeathRecipient, appMgrServiceInner_, pid, appDeathRecipient); handler_->PostTask(addAppRecipientFunc, TASK_ADD_APP_DEATH_RECIPIENT); } @@ -243,7 +241,7 @@ int32_t AppMgrService::ClearUpApplicationData(const std::string &bundleName) } int32_t uid = IPCSkeleton::GetCallingUid(); pid_t pid = IPCSkeleton::GetCallingPid(); - std::function clearUpApplicationDataFunc = + std::function clearUpApplicationDataFunc = std::bind(&AppMgrServiceInner::ClearUpApplicationData, appMgrServiceInner_, bundleName, uid, pid); handler_->PostTask(clearUpApplicationDataFunc, TASK_CLEAR_UP_APPLICATION_DATA); return ERR_OK; @@ -282,6 +280,5 @@ void AppMgrService::GetAppFreezingTime(int &time) appMgrServiceInner_->GetAppFreezingTime(time); APP_LOGE("get app freeze time %{public}d ", time); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service_event_handler.cpp b/services/appmgr/src/app_mgr_service_event_handler.cpp index 85c825b54967983bc723b9c11f000442033e8e0f..2048a74f2a665e58aa6afeb7a9daf4673b74fb61 100644 --- a/services/appmgr/src/app_mgr_service_event_handler.cpp +++ b/services/appmgr/src/app_mgr_service_event_handler.cpp @@ -46,7 +46,6 @@ void AMSEventHandler::ProcessEvent(const InnerEvent::Pointer &event) return; } appManager->HandleTimeOut(event); - // this->PostTask([&event, &appManager]() { appManager->HandleTimeOut(event); }); } } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 29fb059ca382a945d878ea0c4fedfb2e10673c3b..caeb2756c707269aadf060bd6db9099854842396 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -33,7 +33,6 @@ namespace OHOS { namespace AppExecFwk { - using namespace OHOS::Security; namespace { @@ -387,7 +386,7 @@ bool AppMgrServiceInner::process_exist(pid_t &pid) bool AppMgrServiceInner::CheckALLProcessExist(std::list &pids) { - for (auto iter = pids.begin(); iter != pids.end();) { + for (auto iter = pids.begin(); iter != pids.end(); ) { if (!process_exist(*iter) && pids.size() != 0) { pids.erase(iter); if (pids.empty()) { @@ -626,10 +625,10 @@ void AppMgrServiceInner::StartAbility(const sptr &token, const sp } } - auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); - if (abilityRecord && preToken) { + auto ability = appRecord->GetAbilityRunningRecordByToken(token); + if (ability && preToken) { APP_LOGE("Ability is already started"); - abilityRecord->SetPreToken(preToken); + ability->SetPreToken(preToken); return; } @@ -639,21 +638,21 @@ void AppMgrServiceInner::StartAbility(const sptr &token, const sp OptimizerAppStateChanged(appRecord, ApplicationState::APP_STATE_SUSPENDED); } - abilityRecord = appRecord->AddAbility(token, abilityInfo); - if (!abilityRecord) { + ability = appRecord->AddAbility(token, abilityInfo); + if (!ability) { APP_LOGE("add ability failed"); return; } if (preToken != nullptr) { - abilityRecord->SetPreToken(preToken); + ability->SetPreToken(preToken); } if (appState == ApplicationState::APP_STATE_CREATE) { APP_LOGE("in create state, don't launch ability"); return; } - appRecord->LaunchAbility(abilityRecord); + appRecord->LaunchAbility(ability); } std::shared_ptr AppMgrServiceInner::GetAppRunningRecordByAbilityToken( @@ -748,11 +747,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 +783,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_process_manager.cpp b/services/appmgr/src/app_process_manager.cpp index ad38b19e577d6aae9e17d7310d928296aff6d7f6..1bcce2bca54f8f13958f319e47432425eea81b1b 100644 --- a/services/appmgr/src/app_process_manager.cpp +++ b/services/appmgr/src/app_process_manager.cpp @@ -20,9 +20,7 @@ #include "app_log_wrapper.h" namespace OHOS { - namespace AppExecFwk { - AppProcessManager::AppProcessManager() {} @@ -91,6 +89,5 @@ std::shared_ptr AppProcessManager::GetAppTaskInfoByProcessName( }); return ((iter == recentAppList_.end()) ? nullptr : *iter); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index c42cdbf13f8e2bf64f222810fe654bfe29ecf2c0..74c987f3a667437df493e7cfbbed333cbb20b335 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -23,16 +23,12 @@ #include "appexecfwk_errors.h" namespace OHOS { - namespace AppExecFwk { - namespace { - bool CheckUid(const int32_t uid) { return uid >= 0 && uid < std::numeric_limits::max(); } - } // namespace AppRunningManager::AppRunningManager() @@ -198,7 +194,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 +203,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 +255,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..d5c6f1a9a7b8f364e54ae1dd34050926aba52e90 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - int64_t AppRunningRecord::appEventId_ = 0; AppRunningRecord::AppRunningRecord( const std::shared_ptr &info, const int32_t recordId, const std::string &processName) @@ -125,7 +124,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 +257,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 +316,10 @@ void AppRunningRecord::AbilityForeground(const std::shared_ptrOnAppStateChanged(shared_from_this(), curState_); + } } else { APP_LOGW("wrong application state"); } @@ -359,6 +386,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 +419,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/app_spawn_client.cpp b/services/appmgr/src/app_spawn_client.cpp index 889642cb78bef7ae746938df051cddf383610000..ffdb1d5a7cf0837a951d390dc2c3441a5bc1caca 100644 --- a/services/appmgr/src/app_spawn_client.cpp +++ b/services/appmgr/src/app_spawn_client.cpp @@ -20,10 +20,8 @@ namespace OHOS { namespace AppExecFwk { namespace { - const int32_t CONNECT_RETRY_DELAY = 200 * 1000; // 200ms const int32_t CONNECT_RETRY_MAX_TIMES = 15; - } // namespace AppSpawnClient::AppSpawnClient() @@ -132,6 +130,5 @@ void AppSpawnClient::SetSocket(const std::shared_ptr socket) { socket_ = socket; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_spawn_msg_wrapper.cpp b/services/appmgr/src/app_spawn_msg_wrapper.cpp index bd85457b4f9aad090062e0b2067343d638d7496c..8353150f4729bce5d6d09ea867c40f4e995f1446 100644 --- a/services/appmgr/src/app_spawn_msg_wrapper.cpp +++ b/services/appmgr/src/app_spawn_msg_wrapper.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace AppExecFwk { - AppSpawnMsgWrapper::~AppSpawnMsgWrapper() { FreeMsg(); @@ -119,6 +118,5 @@ void AppSpawnMsgWrapper::FreeMsg() isValid_ = false; } } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_spawn_socket.cpp b/services/appmgr/src/app_spawn_socket.cpp index 546b114c06aa05e7ed6418300a3a81db8b9010f2..327b5255cee3cbc79a513c0b3027c839cc3fbb39 100644 --- a/services/appmgr/src/app_spawn_socket.cpp +++ b/services/appmgr/src/app_spawn_socket.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - // arg "AppSpawn" cannot be defined as string object since REGISTER_SYSTEM_ABILITY will // firstly start without init this string object, which leads to error. @@ -106,6 +105,5 @@ void AppSpawnSocket::SetClientSocket(const std::shared_ptr +#include +#include +#include #include -#include #include -#include -#include #include #include #include @@ -25,34 +26,19 @@ #include "event_handler.h" #include "securec.h" -#define CG_CPUSET_DIR "/dev/cpuset" -#define CG_CPUSET_DEFAULT_DIR CG_CPUSET_DIR -#define CG_CPUSET_DEFAULT_TASKS_PATH CG_CPUSET_DEFAULT_DIR "/tasks" -#define CG_CPUSET_BACKGROUND_DIR CG_CPUSET_DIR "/background" -#define CG_CPUSET_BACKGROUND_TASKS_PATH CG_CPUSET_BACKGROUND_DIR "/tasks" - -#define CG_CPUCTL_DIR "/dev/cpuctl" -#define CG_CPUCTL_DEFAULT_DIR CG_CPUCTL_DIR -#define CG_CPUCTL_DEFAULT_TASKS_PATH CG_CPUCTL_DEFAULT_DIR "/tasks" -#define CG_CPUCTL_BACKGROUND_DIR CG_CPUCTL_DIR "/background" -#define CG_CPUCTL_BACKGROUND_TASKS_PATH CG_CPUCTL_BACKGROUND_DIR "/tasks" - -#define CG_FREEZER_DIR "/dev/freezer" -#define CG_FREEZER_FROZEN_DIR CG_FREEZER_DIR "/frozen" -#define CG_FREEZER_FROZEN_TASKS_PATH CG_FREEZER_FROZEN_DIR "/tasks" -#define CG_FREEZER_THAWED_DIR CG_FREEZER_DIR "/thawed" -#define CG_FREEZER_THAWED_TASKS_PATH CG_FREEZER_THAWED_DIR "/tasks" - -#define CG_MEM_DIR "/dev/memcg" -#define CG_MEM_OOMCTL_PATH CG_MEM_DIR "/memory.oom_control" -#define CG_MEM_EVTCTL_PATH CG_MEM_DIR "/cgroup.event_control" -#define CG_MEM_PRESSURE_LEVEL_PATH CG_MEM_DIR "/memory.pressure_level" +constexpr std::string_view CG_CPUSET_DEFAULT_TASKS_PATH("/dev/cpuset/tasks"); +constexpr std::string_view CG_CPUSET_BACKGROUND_TASKS_PATH("/dev/cpuset/background/tasks"); +constexpr std::string_view CG_CPUCTL_DEFAULT_TASKS_PATH("/dev/cpuctl/tasks"); +constexpr std::string_view CG_CPUCTL_BACKGROUND_TASKS_PATH("/dev/cpuctl/background/tasks"); +constexpr std::string_view CG_FREEZER_FROZEN_TASKS_PATH("/dev/freezer/frozen/tasks"); +constexpr std::string_view CG_FREEZER_THAWED_TASKS_PATH("/dev/freezer/thawed/tasks"); +[[maybe_unused]] constexpr std::string_view CG_MEM_OOMCTL_PATH("/dev/memcg/memory.oom_control"); +constexpr std::string_view CG_MEM_EVTCTL_PATH("/dev/memcg/cgroup.event_control"); +constexpr std::string_view CG_MEM_PRESSURE_LEVEL_PATH("/dev/memcg/memory.pressure_level"); namespace OHOS { namespace AppExecFwk { - namespace { - class ScopeGuard final { public: using Function = std::function; @@ -114,17 +100,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() { @@ -144,7 +121,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]); } @@ -165,38 +142,12 @@ bool CgroupManager::Init() return false; } - UniqueFd cpusetTasksFds[SCHED_POLICY_MAX]; - if (!InitCpusetTasksFds(cpusetTasksFds)) { - return false; - } - - UniqueFd cpuctlTasksFds[SCHED_POLICY_MAX]; - if (!InitCpuctlTasksFds(cpuctlTasksFds)) { - return false; - } - - UniqueFd freezerTasksFds[SCHED_POLICY_FREEZER_MAX]; - if (!InitFreezerTasksFds(freezerTasksFds)) { - return false; - } - - UniqueFd memoryEventControlFd; - if (!InitMemoryEventControlFd(memoryEventControlFd)) { - return false; - } - - UniqueFd memoryEventFds[LOW_MEMORY_LEVEL_MAX]; - if (!InitMemoryEventFds(memoryEventFds)) { - return false; - } - - UniqueFd memoryPressureFds[LOW_MEMORY_LEVEL_MAX]; - if (!InitMemoryPressureFds(memoryPressureFds)) { + if(!InitCheck()){ return false; } if (!RegisterLowMemoryMonitor( - memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_LOW, eventHandler)) { + memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_LOW, eventHandler)) { return false; } @@ -204,7 +155,7 @@ bool CgroupManager::Init() [&]() { eventHandler->RemoveFileDescriptorListener(memoryEventFds_[LOW_MEMORY_LEVEL_LOW]); }); if (!RegisterLowMemoryMonitor( - memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_MEDIUM, eventHandler)) { + memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_MEDIUM, eventHandler)) { return false; } @@ -212,7 +163,7 @@ bool CgroupManager::Init() [&]() { eventHandler->RemoveFileDescriptorListener(memoryEventFds_[LOW_MEMORY_LEVEL_MEDIUM]); }); if (!RegisterLowMemoryMonitor( - memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_CRITICAL, eventHandler)) { + memoryEventFds_, memoryPressureFds_, memoryEventControlFd_, LOW_MEMORY_LEVEL_CRITICAL, eventHandler)) { return false; } @@ -220,7 +171,6 @@ bool CgroupManager::Init() [&]() { eventHandler->RemoveFileDescriptorListener(memoryEventFds_[LOW_MEMORY_LEVEL_CRITICAL]); }); eventHandler_ = eventHandler; - lowLevelListenerGuard.Dismiss(); mediumLevelListenerGuard.Dismiss(); criticalLevelListenerGuard.Dismiss(); @@ -228,6 +178,40 @@ bool CgroupManager::Init() return true; } +bool CgroupManager::InitCheck() +{ + UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_MAX]; + if (!InitCpusetTasksFds(cpusetTasksFds)) { + return false; + } + + UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_MAX]; + if (!InitCpuctlTasksFds(cpuctlTasksFds)) { + return false; + } + + UniqueFd freezerTasksFds[SCHED_POLICY_FREEZER_MAX]; + if (!InitFreezerTasksFds(freezerTasksFds)) { + return false; + } + + UniqueFd memoryEventControlFd; + if (!InitMemoryEventControlFd(memoryEventControlFd)) { + return false; + } + + UniqueFd memoryEventFds[LOW_MEMORY_LEVEL_MAX]; + if (!InitMemoryEventFds(memoryEventFds)) { + return false; + } + + UniqueFd memoryPressureFds[LOW_MEMORY_LEVEL_MAX]; + if (!InitMemoryPressureFds(memoryPressureFds)) { + return false; + } + return true; +} + bool CgroupManager::IsInited() const { return bool(eventHandler_); @@ -356,11 +340,8 @@ void CgroupManager::OnReadable(int32_t fd) return false; } if (count < 1) { -#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 + APP_LOGW( + "%{public}s(%{public}d) invalid eventfd count %{public}" PRIu64 ".", __func__, __LINE__, count); return false; } APP_LOGW( @@ -397,12 +378,12 @@ bool CgroupManager::RegisterLowMemoryMonitor(const int memoryEventFds[LOW_MEMORY static const char *levelName[] = {"low", "medium", "critical"}; if (snprintf_s(buf, - sizeof(buf), - sizeof(buf) - 1, - "%d %d %s", - memoryEventFds[level], - memoryPressureFds[level], - levelName[level]) < 0) { + sizeof(buf), + sizeof(buf) - 1, + "%d %d %s", + memoryEventFds[level], + memoryPressureFds[level], + levelName[level]) < 0) { return false; } @@ -419,8 +400,8 @@ bool CgroupManager::RegisterLowMemoryMonitor(const int memoryEventFds[LOW_MEMORY bool CgroupManager::InitCpusetTasksFds(UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_MAX]) { - cpusetTasksFds[SCHED_POLICY_CPU_DEFAULT] = UniqueFd(open(CG_CPUSET_DEFAULT_TASKS_PATH, O_RDWR)); - cpusetTasksFds[SCHED_POLICY_CPU_BACKGROUND] = UniqueFd(open(CG_CPUSET_BACKGROUND_TASKS_PATH, O_RDWR)); + cpusetTasksFds[SCHED_POLICY_CPU_DEFAULT] = UniqueFd(open(CG_CPUSET_DEFAULT_TASKS_PATH.data(), O_RDWR)); + cpusetTasksFds[SCHED_POLICY_CPU_BACKGROUND] = UniqueFd(open(CG_CPUSET_BACKGROUND_TASKS_PATH.data(), O_RDWR)); if (cpusetTasksFds[SCHED_POLICY_CPU_DEFAULT].Get() < 0 || cpusetTasksFds[SCHED_POLICY_CPU_BACKGROUND].Get() < 0) { APP_LOGE("%{public}s(%{public}d) cannot open cpuset cgroups %{public}d.", __func__, __LINE__, errno); return false; @@ -433,8 +414,8 @@ bool CgroupManager::InitCpusetTasksFds(UniqueFd cpusetTasksFds[SCHED_POLICY_CPU_ bool CgroupManager::InitCpuctlTasksFds(UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_MAX]) { - cpuctlTasksFds[SCHED_POLICY_CPU_DEFAULT] = UniqueFd(open(CG_CPUCTL_DEFAULT_TASKS_PATH, O_RDWR)); - cpuctlTasksFds[SCHED_POLICY_CPU_BACKGROUND] = UniqueFd(open(CG_CPUCTL_BACKGROUND_TASKS_PATH, O_RDWR)); + cpuctlTasksFds[SCHED_POLICY_CPU_DEFAULT] = UniqueFd(open(CG_CPUCTL_DEFAULT_TASKS_PATH.data(), O_RDWR)); + cpuctlTasksFds[SCHED_POLICY_CPU_BACKGROUND] = UniqueFd(open(CG_CPUCTL_BACKGROUND_TASKS_PATH.data(), O_RDWR)); if (cpuctlTasksFds[SCHED_POLICY_CPU_DEFAULT].Get() < 0 || cpuctlTasksFds[SCHED_POLICY_CPU_BACKGROUND].Get() < 0) { APP_LOGE("%{public}s(%{public}d) cannot open cpuctl cgroups %{public}d.", __func__, __LINE__, errno); return false; @@ -447,8 +428,8 @@ bool CgroupManager::InitCpuctlTasksFds(UniqueFd cpuctlTasksFds[SCHED_POLICY_CPU_ bool CgroupManager::InitFreezerTasksFds(UniqueFd freezerTasksFds[SCHED_POLICY_FREEZER_MAX]) { - freezerTasksFds[SCHED_POLICY_FREEZER_FROZEN] = UniqueFd(open(CG_FREEZER_FROZEN_TASKS_PATH, O_RDWR)); - freezerTasksFds[SCHED_POLICY_FREEZER_THAWED] = UniqueFd(open(CG_FREEZER_THAWED_TASKS_PATH, O_RDWR)); + freezerTasksFds[SCHED_POLICY_FREEZER_FROZEN] = UniqueFd(open(CG_FREEZER_FROZEN_TASKS_PATH.data(), O_RDWR)); + freezerTasksFds[SCHED_POLICY_FREEZER_THAWED] = UniqueFd(open(CG_FREEZER_THAWED_TASKS_PATH.data(), O_RDWR)); if (freezerTasksFds[SCHED_POLICY_FREEZER_FROZEN].Get() < 0 || freezerTasksFds[SCHED_POLICY_FREEZER_THAWED].Get() < 0) { APP_LOGE("%{public}s(%{public}d) cannot open freezer cgroups %{public}d.", __func__, __LINE__, errno); @@ -462,7 +443,7 @@ bool CgroupManager::InitFreezerTasksFds(UniqueFd freezerTasksFds[SCHED_POLICY_FR bool CgroupManager::InitMemoryEventControlFd(UniqueFd &memoryEventControlFd) { - memoryEventControlFd = UniqueFd(open(CG_MEM_EVTCTL_PATH, O_WRONLY)); + memoryEventControlFd = UniqueFd(open(CG_MEM_EVTCTL_PATH.data(), O_WRONLY)); if (memoryEventControlFd.Get() < 0) { APP_LOGE( "%{pubid}s(%{publid}d) failed to open memory event control node %{public}d.", __func__, __LINE__, errno); @@ -492,9 +473,9 @@ bool CgroupManager::InitMemoryEventFds(UniqueFd memoryEventFds[LOW_MEMORY_LEVEL_ bool CgroupManager::InitMemoryPressureFds(UniqueFd memoryPressureFds[LOW_MEMORY_LEVEL_MAX]) { - memoryPressureFds[LOW_MEMORY_LEVEL_LOW] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH, O_RDONLY)); - memoryPressureFds[LOW_MEMORY_LEVEL_MEDIUM] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH, O_RDONLY)); - memoryPressureFds[LOW_MEMORY_LEVEL_CRITICAL] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH, O_RDONLY)); + memoryPressureFds[LOW_MEMORY_LEVEL_LOW] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH.data(), O_RDONLY)); + memoryPressureFds[LOW_MEMORY_LEVEL_MEDIUM] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH.data(), O_RDONLY)); + memoryPressureFds[LOW_MEMORY_LEVEL_CRITICAL] = UniqueFd(open(CG_MEM_PRESSURE_LEVEL_PATH.data(), O_RDONLY)); if (memoryPressureFds[LOW_MEMORY_LEVEL_LOW].Get() < 0 || memoryPressureFds[LOW_MEMORY_LEVEL_MEDIUM].Get() < 0 || memoryPressureFds[LOW_MEMORY_LEVEL_CRITICAL].Get() < 0) { APP_LOGE("%{public}s(${public}d) failed to open memory pressure fd %{public}d.", __func__, __LINE__, errno); @@ -557,6 +538,5 @@ bool CgroupManager::SetFreezerSubsystem(const int tid, const SchedPolicyFreezer return true; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/lmks/lmks_main.cpp b/services/appmgr/src/lmks/lmks_main.cpp index 117eef80302a93c493c44e888c7019b580b5f969..e90fead4a50319e18c46d784f08bc90bb40ec9f7 100644 --- a/services/appmgr/src/lmks/lmks_main.cpp +++ b/services/appmgr/src/lmks/lmks_main.cpp @@ -15,8 +15,10 @@ #include "lmks_server.h" -int main(int argc, char *const argv[]) +int main(int argc, char *argv[]) { + (void)argc; + (void)argv; OHOS::LMKS::LmksServer lmksServer; lmksServer.StartServer(); diff --git a/services/appmgr/src/lmks/lmks_server.cpp b/services/appmgr/src/lmks/lmks_server.cpp index 59a33fbe3ac88e58b2f5144faa00c89e0c7078ff..dfed0e4605645498c88c7cc2f33fcdc089498296 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,32 +257,31 @@ 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. close(connectFd); } - } // namespace LMKS } // namespace OHOS diff --git a/services/appmgr/src/lmks/lmks_utils.cpp b/services/appmgr/src/lmks/lmks_utils.cpp index 1066ee8d8d51b8619a4f71b48a6754701968211f..ea37d7eb8eac645a1f89153fc943e31d8a3c8452 100644 --- a/services/appmgr/src/lmks/lmks_utils.cpp +++ b/services/appmgr/src/lmks/lmks_utils.cpp @@ -15,7 +15,7 @@ #include "lmks_utils.h" -#include +#include #include #include #include @@ -25,7 +25,6 @@ namespace OHOS { namespace LMKS { - namespace { constexpr int PROC_PATH_MAX = 256; constexpr int PROC_LINE_MAX = 128; @@ -60,7 +59,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 +103,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) + 1 <= PROC_LINE_MAX && strlen(line) != 0 && line[strlen(line)] == '\0') { name = line; } else { HiLog::Error(LABEL, "cmdline no data"); @@ -159,8 +159,7 @@ int LmksUtils::GetProcSize(pid_t pid) return -1; } - if ((strlen(line) != 0) && - (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { + if ((strlen(line) + 1 <= 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 +192,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/lmks_client.cpp b/services/appmgr/src/lmks_client.cpp index df857c60fa2fff962c977c97fac30a8bf5d7fcff..f0c288b984af987503af16546eae26bc558bd8a9 100644 --- a/services/appmgr/src/lmks_client.cpp +++ b/services/appmgr/src/lmks_client.cpp @@ -15,7 +15,7 @@ #include "lmks_client.h" -#include +#include #include #include #include @@ -31,10 +31,11 @@ namespace OHOS { namespace AppExecFwk { - namespace { constexpr int LMKS_SOCKET_TIMEOUT = 3; +constexpr size_t LMKS_START_VALUE = 1; +constexpr size_t LMKS_MULTIPLE = 2; constexpr size_t LMKS_MAX_TARGETS = 6; constexpr int LMKS_CMD_TARGET = 0; @@ -145,7 +146,7 @@ int32_t LmksClient::Target(const Targets &targets) } int i = 0; - int32_t buf[1 + 2 * LMKS_MAX_TARGETS]; + int32_t buf[LMKS_START_VALUE + LMKS_MULTIPLE * LMKS_MAX_TARGETS]; buf[i++] = LMKS_CMD_TARGET; for (auto target : targets) { diff --git a/services/appmgr/src/process_optimizer.cpp b/services/appmgr/src/process_optimizer.cpp index da02f7a07a5ed7862ec4fb870ac8455c79a9e57e..e3cf6bc23eb0f5e42d919980dbb6220d2731bb2f 100644 --- a/services/appmgr/src/process_optimizer.cpp +++ b/services/appmgr/src/process_optimizer.cpp @@ -16,19 +16,18 @@ #include "process_optimizer.h" #include +#include #include -#include - #include "app_log_wrapper.h" -#define APP_SUSPEND_TIMER_NAME_PREFIX "AppSuspendTimer" - namespace OHOS { namespace AppExecFwk { using namespace std::placeholders; namespace { +constexpr auto APP_SUSPEND_TIMER_NAME_PREFIX = "AppSuspendTimer"; + constexpr int APP_OOM_ADJ_SYSTEM = -100; // foreground process oom_adj constexpr int APP_OOM_ADJ_FOREGROUND = 0; @@ -54,7 +53,7 @@ constexpr int APP_OOM_ADJ_SUSPEND_MAX = 799; constexpr int APP_OOM_ADJ_SUSPEND_MAX_VALUE = 24 * 1024; // empty process oom_adj -// constexpr int APP_OOM_ADJ_EMPTY_MIN = 800; +[[maybe_unused]] constexpr int APP_OOM_ADJ_EMPTY_MIN = 800; constexpr int APP_OOM_ADJ_EMPTY_MAX = 999; constexpr int APP_OOM_ADJ_EMPTY_MAX_VALUE = 32 * 1024; @@ -63,6 +62,8 @@ constexpr int APP_OOM_ADJ_UNKNOWN_VALUE = 64 * 1024; constexpr std::string_view SYSTEM_UI_BUNDLE_NAME = "com.ohos.systemui"; +constexpr int TIME_ADVANCE_RATE = 1000; + // pressure level low constexpr int LMKS_OOM_ADJ_LOW = 800; // pressure level medium @@ -478,14 +479,12 @@ bool ProcessOptimizer::UpdateAppOomAdj(const AppPtr &app) APP_LOGE("%{public}s(%{public}d) invalid priority object.", __func__, __LINE__); return false; } - // special set launcher and systemui adj if (app->IsLauncherApp() || app->GetBundleName() == SYSTEM_UI_BUNDLE_NAME) { return SetAppOomAdj(app, APP_OOM_ADJ_SYSTEM); } auto state = app->GetState(); - if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_CREATE || state == ApplicationState::APP_STATE_READY) { return SetAppOomAdj(app, APP_OOM_ADJ_FOREGROUND); @@ -493,6 +492,34 @@ bool ProcessOptimizer::UpdateAppOomAdj(const AppPtr &app) int oomAdj; int oomAdjMax; + if(!GetAppOomAdj(app,state,oomAdj, oomAdjMax)){ + return false; + } + + for (auto curApp : appLru_) { + if (curApp->GetState() != state) { + continue; + } + // adj of launcher and systemui is always APP_OOM_ADJ_SYSTEM + if (curApp->IsLauncherApp() || curApp->GetBundleName() == SYSTEM_UI_BUNDLE_NAME) { + continue; + } + + SetAppOomAdj(curApp, oomAdj); + if (oomAdj < oomAdjMax) { + oomAdj += 1; + } + } + return true; +} + +bool ProcessOptimizer::GetAppOomAdj(const AppPtr &app,ApplicationState state,int &oomAdj,int &oomAdjMax) +{ + auto priorityObject = app->GetPriorityObject(); + if (!priorityObject) { + APP_LOGE("%{public}s(%{public}d) invalid priority object.", __func__, __LINE__); + return false; + } switch (state) { case ApplicationState::APP_STATE_BACKGROUND: @@ -520,23 +547,6 @@ bool ProcessOptimizer::UpdateAppOomAdj(const AppPtr &app) oomAdjMax = APP_OOM_ADJ_UNKNOWN; break; } - - for (auto curApp : appLru_) { - if (curApp->GetState() != state) { - continue; - } - - // adj of launcher and systemui is always APP_OOM_ADJ_SYSTEM - if (curApp->IsLauncherApp() || curApp->GetBundleName() == SYSTEM_UI_BUNDLE_NAME) { - continue; - } - - SetAppOomAdj(curApp, oomAdj); - if (oomAdj < oomAdjMax) { - oomAdj += 1; - } - } - return true; } @@ -567,7 +577,6 @@ bool ProcessOptimizer::UpdateAppSchedPolicy(const AppPtr &app) ret = true; break; } - return ret; } @@ -607,13 +616,13 @@ void ProcessOptimizer::StartAppSuspendTimer(const AppPtr &app) eventHandler_->PostTask( [=]() { - auto it = suspendTimers_.find(timerName); - if (it != suspendTimers_.end()) { + auto finder = suspendTimers_.find(timerName); + if (finder != suspendTimers_.end()) { APP_LOGD("%{public}s(%{public}d) removing app '%{public}s' suspend timer name...", timerName.c_str(), __LINE__, app->GetName().c_str()); - suspendTimers_.erase(it); + suspendTimers_.erase(finder); } else { APP_LOGE("%{public}s(%{public}d) invalid suspend timer for app '%{public}s'.", timerName.c_str(), @@ -700,24 +709,19 @@ 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; } suspendTimeout_ = time; // convert seconds to milliseconds - suspendTimeout_ *= 1000; - if (suspendTimeout_ > INT_MAX) { - suspendTimeout_ = APP_SUSPEND_TIMEOUT_DEFAULT; - APP_LOGE("data overflow"); - return; - } + suspendTimeout_ *= TIME_ADVANCE_RATE; } void ProcessOptimizer::GetAppFreezingTime(int &time) { - time = suspendTimeout_ / 1000; + time = suspendTimeout_ / TIME_ADVANCE_RATE; APP_LOGE("%{public}s current freez time:[%{public}d]", __func__, time); return; } diff --git a/services/appmgr/src/process_optimizer_uba.cpp b/services/appmgr/src/process_optimizer_uba.cpp index 12d85fe33a3362db3c68810a85240dadcc68e603..9e01e969e3fe8a80af9775e5bd6308c72fb9a50b 100644 --- a/services/appmgr/src/process_optimizer_uba.cpp +++ b/services/appmgr/src/process_optimizer_uba.cpp @@ -18,7 +18,6 @@ namespace OHOS { namespace AppExecFwk { - ProcessOptimizerUBA::BaseAbilityAction::BaseAbilityAction(const AbilityPtr &ability) : time_(Clock::now()), name_(ability->GetName()) {} @@ -32,7 +31,7 @@ std::string ProcessOptimizerUBA::BaseAbilityAction::GetTimeString() const { std::time_t tmp = Clock::to_time_t(time_); char *pTime = std::ctime(&tmp); - return pTime == nullptr ? "" : std::string(pTime); + return (pTime == nullptr) ? "" : std::string(pTime); } const std::string &ProcessOptimizerUBA::BaseAbilityAction::GetName() const @@ -289,7 +288,6 @@ void ProcessOptimizerUBA::CommitAbilityActions() { auto n = abilityActionCount_; abilityActionCount_ = 0; - auto ubaService = GetUbaService(); if (!ubaService) { APP_LOGE("%{public}s(%{pubic}d) uba is not available.", __func__, __LINE__); @@ -303,61 +301,82 @@ void ProcessOptimizerUBA::CommitAbilityActions() auto startAbilityAction = std::get_if(&abilityAction); if (startAbilityAction) { - APP_LOGD(" [%{public}zu] %{public}s ability '%{public}s' starts '%{public}s'", - i, - startAbilityAction->GetTimeString().c_str(), - startAbilityAction->GetPreName().c_str(), - startAbilityAction->GetName().c_str()); - // commit action + CommitStartAbilityAction(*startAbilityAction, i); continue; } - auto connectAbilityAction = std::get_if(&abilityAction); if (connectAbilityAction) { - APP_LOGD(" [%{public}zu] %{public}s ability '%{public}s' connect to '%{public}s'", - i, - connectAbilityAction->GetTimeString().c_str(), - connectAbilityAction->GetName().c_str(), - connectAbilityAction->GetTargetName().c_str()); - // commit action + CommitConnectAbilityAction(*connectAbilityAction, i); continue; } - auto disconnectAbilityAction = std::get_if(&abilityAction); if (disconnectAbilityAction) { - APP_LOGD(" [%{public}zu] %{public}s '%{public}s' ability disconnect with '%{public}s'", - i, - disconnectAbilityAction->GetTimeString().c_str(), - disconnectAbilityAction->GetName().c_str(), - disconnectAbilityAction->GetTargetName().c_str()); - // commit action + CommitDisconnectAbilityAction(*disconnectAbilityAction, i); continue; } - auto changedAbilityStateAction = std::get_if(&abilityAction); if (changedAbilityStateAction) { - APP_LOGD(" [%{public}zu] %{public}s ability '%{public}s' state changed from %{public}d to %{public}d.", - i, - changedAbilityStateAction->GetTimeString().c_str(), - changedAbilityStateAction->GetName().c_str(), - changedAbilityStateAction->GetOldState(), - changedAbilityStateAction->GetNewState()); - // commit action + CommitChangedAbilityStateAction(*changedAbilityStateAction, i); continue; } - auto removeAbilityAction = std::get_if(&abilityAction); if (removeAbilityAction) { - APP_LOGD(" [%{public}zu] %{public}s '%{public}s' removed.", - i, - removeAbilityAction->GetTimeString().c_str(), - removeAbilityAction->GetName().c_str()); - // commit action + CommitRemoveAbilityAction(*removeAbilityAction, i); continue; } } } +void ProcessOptimizerUBA::CommitStartAbilityAction(const StartAbilityAction& action, size_t index) +{ + APP_LOGD(" [%{public}zu] %{public}s ability '%{public}s' starts '%{public}s'", + index, + action.GetTimeString().c_str(), + action.GetPreName().c_str(), + action.GetName().c_str()); + // commit action +} + +void ProcessOptimizerUBA::CommitConnectAbilityAction(const ConnectAbilityAction& action, size_t index) +{ + APP_LOGD(" [%{public}zu] %{public}s ability '%{public}s' connect to '%{public}s'", + index, + action.GetTimeString().c_str(), + action.GetName().c_str(), + action.GetTargetName().c_str()); + // commit action +} + +void ProcessOptimizerUBA::CommitDisconnectAbilityAction(const DisconnectAbilityAction& action, size_t index) +{ + APP_LOGD(" [%{public}zu] %{public}s '%{public}s' ability disconnect with '%{public}s'", + index, + action.GetTimeString().c_str(), + action.GetName().c_str(), + action.GetTargetName().c_str()); + // commit action +} + +void ProcessOptimizerUBA::CommitChangedAbilityStateAction(const ChangeAbilityStateAction& action, size_t index) +{ + APP_LOGD(" [%{public}zu] %{public}s ability '%{public}s' state changed from %{public}d to %{public}d.", + index, + action.GetTimeString().c_str(), + action.GetName().c_str(), + action.GetOldState(), + action.GetNewState()); + // commit action +} + +void ProcessOptimizerUBA::CommitRemoveAbilityAction(const RemoveAbilityAction& action, size_t index) +{ + APP_LOGD(" [%{public}zu] %{public}s '%{public}s' removed.", + index, + action.GetTimeString().c_str(), + action.GetName().c_str()); + // commit action +} + UbaServicePtr ProcessOptimizerUBA::GetUbaService() { if (ubaService_) { @@ -387,6 +406,5 @@ void ProcessOptimizerUBA::GetAppFreezingTime(int &time) ProcessOptimizer::GetAppFreezingTime(time); } } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/remote_client_manager.cpp b/services/appmgr/src/remote_client_manager.cpp index ac024d0e8d6d8e13aec0db5ce057e6b8b297b5e8..711b395c0d57de2491df62c07cafaf88066a5ff5 100644 --- a/services/appmgr/src/remote_client_manager.cpp +++ b/services/appmgr/src/remote_client_manager.cpp @@ -21,9 +21,7 @@ #include "app_log_wrapper.h" namespace OHOS { - namespace AppExecFwk { - RemoteClientManager::RemoteClientManager() : appSpawnClient_(std::make_shared()) {} @@ -61,6 +59,5 @@ void RemoteClientManager::SetBundleManager(sptr bundleManager) { bundleManager_ = bundleManager; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/start_via_asan.cpp b/services/appmgr/src/start_via_asan.cpp index decc6438e5a368936face2aef141003d3944f33a..5eb2d1d29275edfabdc50f009004451ee8b76ca5 100644 --- a/services/appmgr/src/start_via_asan.cpp +++ b/services/appmgr/src/start_via_asan.cpp @@ -14,14 +14,11 @@ */ #include "start_via_asan.h" - #include "properties.h" - #include "app_log_wrapper.h" namespace OHOS { namespace AppExecFwk { - StartViaAsan::StartViaAsan() {} @@ -54,6 +51,5 @@ void StartViaAsan::GetAsanStartMsg(AppSpawnStartMsg &startMsg) const } startMsg.argsNum++; } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/mock/include/mock_ability_token.h b/services/appmgr/test/mock/include/mock_ability_token.h index ffee93df53ed1dd1cfb39d88f44c9bedc9dc9e49..2a43c7d652a418eec9212b9f478f89def85c7847 100644 --- a/services/appmgr/test/mock/include/mock_ability_token.h +++ b/services/appmgr/test/mock/include/mock_ability_token.h @@ -24,11 +24,11 @@ namespace OHOS { namespace AppExecFwk { - class IAbilityToken : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AbilityToken"); }; +DECLARE_INTERFACE_DESCRIPTOR(u"IAbilityToken"); class MockAbilityToken : public IRemoteStub { public: @@ -54,9 +54,6 @@ public: private: DISALLOW_COPY_AND_MOVE(AbilityTokenProxy); }; - -DECLARE_INTERFACE_DESCRIPTOR(u"IAbilityToken"); - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_ABILITY_TOKEN_H diff --git a/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h b/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h index fd3d79275557492de992f418ab72334d7cbe7a74..2b5aaeeb4735ee73b78e4c79c342873ae0978923 100644 --- a/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h +++ b/services/appmgr/test/mock/include/mock_ams_mgr_scheduler.h @@ -21,18 +21,14 @@ namespace OHOS { namespace AppExecFwk { - class MockAmsMgrScheduler : public AmsMgrStub { - public: MOCK_METHOD4(LoadAbility, void(const sptr &token, const sptr &preToken, const std::shared_ptr &abilityInfo, const std::shared_ptr &appInfo)); - MOCK_METHOD5(AbilityBehaviorAnalysis, void(const sptr &token, const sptr &preToken, const int32_t visibility, const int32_t perceptibility, const int32_t connectionState)); - MOCK_METHOD1(TerminateAbility, void(const sptr &token)); MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); MOCK_METHOD0(Reset, void()); @@ -41,10 +37,8 @@ public: MOCK_METHOD0(IsReady, bool()); MOCK_METHOD1(AbilityAttachTimeOut, void(const sptr &token)); MOCK_METHOD4(CompelVerifyPermission, int(const std::string &permission, int pid, int uid, std::string &message)); - MockAmsMgrScheduler() : AmsMgrStub(){}; virtual ~MockAmsMgrScheduler(){}; - virtual void RegisterAppStateCallback(const sptr &callback) override { callback->OnAbilityRequestDone(nullptr, AbilityState::ABILITY_STATE_BACKGROUND); @@ -52,7 +46,6 @@ public: callback->OnAppStateChanged(appProcessData); } }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service.h b/services/appmgr/test/mock/include/mock_app_mgr_service.h index e10cf628c2698d5a1dee727b9ce6d53cc95b2e57..3be54288ae3cff27d7501afcd6ff51debf979cb4 100644 --- a/services/appmgr/test/mock/include/mock_app_mgr_service.h +++ b/services/appmgr/test/mock/include/mock_app_mgr_service.h @@ -94,13 +94,11 @@ public: AbilityState st = AbilityState::ABILITY_STATE_BEGIN; callback_->OnAbilityRequestDone(token, st); } - private: Semaphore sem_; std::string data_; sptr callback_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_COMMON_TEST_MOCK_MOCK_APP_MGR_SERVICE_H \ No newline at end of file diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h index 21d2463c013731dfdbc67186635229b50830cc69..635e19f1fa70a28fa346813a27463a3d3852823b 100644 --- a/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h +++ b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h @@ -18,13 +18,11 @@ #include "gmock/gmock.h" #include "app_log_wrapper.h" - #include "semaphore_ex.h" #include "app_mgr_service_inner.h" namespace OHOS { namespace AppExecFwk { - class MockAppMgrServiceInner : public AppMgrServiceInner { public: MockAppMgrServiceInner() : lock_(0) @@ -51,7 +49,6 @@ public: MOCK_CONST_METHOD0(QueryAppSpawnConnectionState, SpawnConnectionState()); MOCK_CONST_METHOD2(AddAppDeathRecipient, void(const pid_t pid, const sptr &appDeathRecipient)); MOCK_METHOD1(KillProcessByAbilityToken, void(const sptr &token)); - MOCK_METHOD5(AbilityBehaviorAnalysis, void(const sptr &token, const sptr &preToken, const int32_t visibility, const int32_t perceptibility, const int32_t connectionState)); @@ -67,7 +64,6 @@ public: currentCount_ = count_; } } - // for mock function return int32_t int32_t Post4Int() { @@ -101,7 +97,6 @@ private: int32_t count_ = 1; int32_t currentCount_ = 1; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_MGR_SERVICE_INNER_H diff --git a/services/appmgr/test/mock/include/mock_app_scheduler.h b/services/appmgr/test/mock/include/mock_app_scheduler.h index c1873d422d8688911f5939371414cd6c9147b268..e3e19822e164b99fcd3dc99c7bb958c5e1b53e40 100644 --- a/services/appmgr/test/mock/include/mock_app_scheduler.h +++ b/services/appmgr/test/mock/include/mock_app_scheduler.h @@ -24,12 +24,10 @@ namespace OHOS { namespace AppExecFwk { - class MockAppScheduler : public AppSchedulerHost { public: MockAppScheduler(){}; virtual ~MockAppScheduler(){}; - MOCK_METHOD0(ScheduleForegroundApplication, void()); MOCK_METHOD0(ScheduleBackgroundApplication, void()); MOCK_METHOD0(ScheduleTerminateApplication, void()); diff --git a/services/appmgr/test/mock/include/mock_app_service_mgr.h b/services/appmgr/test/mock/include/mock_app_service_mgr.h index 16a281468f940c4976fb059cc4aa79f4b42ab3c2..1f9980fb636d9a76178b6003b2b4429bd6b3bb89 100644 --- a/services/appmgr/test/mock/include/mock_app_service_mgr.h +++ b/services/appmgr/test/mock/include/mock_app_service_mgr.h @@ -17,14 +17,12 @@ #define FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_SERVICE_MGR_H #include "iremote_object.h" - #include "app_log_wrapper.h" #include "app_service_manager.h" #include "mock_app_mgr_service.h" namespace OHOS { namespace AppExecFwk { - class MockAppServiceMgr : public AppServiceManager { public: MockAppServiceMgr() = default; @@ -36,7 +34,6 @@ public: return new MockAppMgrService(); } }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APP_SERVICE_MGR_H \ No newline at end of file diff --git a/services/appmgr/test/mock/include/mock_app_spawn_client.h b/services/appmgr/test/mock/include/mock_app_spawn_client.h index 9ca5321263d23eb2be6080c5e25bfd56475af73b..62a5e60e43d5a4b11e393d65996f16fa2a88438d 100644 --- a/services/appmgr/test/mock/include/mock_app_spawn_client.h +++ b/services/appmgr/test/mock/include/mock_app_spawn_client.h @@ -20,7 +20,6 @@ namespace OHOS { namespace AppExecFwk { - class MockAppSpawnClient : public AppSpawnClient { public: MockAppSpawnClient() @@ -29,7 +28,6 @@ public: {} MOCK_METHOD2(StartProcess, ErrCode(const AppSpawnStartMsg &startMsg, pid_t &pid)); }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_CLIENT_H diff --git a/services/appmgr/test/mock/include/mock_app_spawn_socket.h b/services/appmgr/test/mock/include/mock_app_spawn_socket.h index e2f66ae17bf99fca7e3cb212f7a03c0c0b488f98..4a14ec5ee108c0857ada0934989c1e03131a748a 100644 --- a/services/appmgr/test/mock/include/mock_app_spawn_socket.h +++ b/services/appmgr/test/mock/include/mock_app_spawn_socket.h @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - class MockAppSpawnSocket : public AppSpawnSocket { public: MockAppSpawnSocket() = default; @@ -34,7 +33,6 @@ public: MOCK_METHOD0(CloseAppSpawnConnection, void()); MOCK_METHOD2(WriteMessage, ErrCode(const void *buf, const int32_t len)); MOCK_METHOD2(ReadMessage, ErrCode(void *buf, int32_t len)); - ErrCode ReadImpl(void *buf, [[maybe_unused]] int32_t len) { if (buf == nullptr) { @@ -56,7 +54,6 @@ public: private: int32_t expectPid_ = 0; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_UT_MOCK_APP_SPAWN_SOCKET_H diff --git a/services/appmgr/test/mock/include/mock_application.h b/services/appmgr/test/mock/include/mock_application.h index 52b560dbdb78bf6e8e17cc631a54c9bccc35e827..d293858dbefb49f63822cd7d2f4590fc31965a38 100644 --- a/services/appmgr/test/mock/include/mock_application.h +++ b/services/appmgr/test/mock/include/mock_application.h @@ -17,12 +17,10 @@ #include "gmock/gmock.h" #include "semaphore_ex.h" - #include "app_scheduler_host.h" namespace OHOS { namespace AppExecFwk { - class MockApplication : public AppSchedulerHost { public: MOCK_METHOD0(ScheduleForegroundApplication, void()); @@ -108,7 +106,6 @@ private: Profile profile_; // Configuration configuration_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_APPMGR_TEST_MOCK_APPLICATION_H diff --git a/services/appmgr/test/mock/include/mock_bundle_manager.h b/services/appmgr/test/mock/include/mock_bundle_manager.h index 312d5f4182e1e5303e1f48f55ea2178db480cfd5..abe52439eaef7cb825d93f3aa0903a682457d482 100644 --- a/services/appmgr/test/mock/include/mock_bundle_manager.h +++ b/services/appmgr/test/mock/include/mock_bundle_manager.h @@ -17,7 +17,6 @@ #define OHOS_AAFWK_ABILITY_MOCK_BUNDLE_MANAGER_H #include - #include "gmock/gmock.h" #include "ability_info.h" #include "application_info.h" @@ -28,7 +27,6 @@ namespace OHOS { namespace AppExecFwk { - class BundleMgrProxy : public IRemoteProxy { public: explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) @@ -50,7 +48,6 @@ public: 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 bool GetApplicationInfo( @@ -60,6 +57,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; @@ -96,19 +97,16 @@ public: { return ""; }; - virtual bool GetBundleArchiveInfo( const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override { return true; }; virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override; - 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; @@ -174,6 +172,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 +222,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 +340,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,8 +349,17 @@ 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 } // namespace OHOS diff --git a/services/appmgr/test/mock/include/sys_mgr_client.h b/services/appmgr/test/mock/include/sys_mgr_client.h index 45a85087ccf616ffaddf908099d851c781c873e9..5ec7b6906ecdbe3b80687a578e5571b0a8f238c2 100644 --- a/services/appmgr/test/mock/include/sys_mgr_client.h +++ b/services/appmgr/test/mock/include/sys_mgr_client.h @@ -20,14 +20,12 @@ #include #include #include - #include "if_system_ability_manager.h" #include "iremote_object.h" #include "singleton.h" namespace OHOS { namespace AppExecFwk { - class SysMrgClient { DECLARE_DELAYED_SINGLETON(SysMrgClient) public: diff --git a/services/appmgr/test/mock/include/system_ability.h b/services/appmgr/test/mock/include/system_ability.h index f850c8c9c8bb2d607897d92f9487d7bfe59ca1a2..000c49aa6e67de268503ca7ed65547f1a6809f23 100644 --- a/services/appmgr/test/mock/include/system_ability.h +++ b/services/appmgr/test/mock/include/system_ability.h @@ -20,11 +20,9 @@ #include "iremote_object.h" namespace OHOS { - #define REGISTER_SYSTEM_ABILITY_BY_ID(a, b, c) #define REGISTER_SYSTEM_ABILITY(abilityClassName, abilityId, runOnCreate) #define DECLEAR_SYSTEM_ABILITY(className) - static constexpr HiviewDFX::HiLogLabel LABEL = {LOG_CORE, 0xD001100, "MockSystemAbility"}; class SystemAbility { diff --git a/services/appmgr/test/mock/src/cgroup_manager.cpp b/services/appmgr/test/mock/src/cgroup_manager.cpp index 92093c088f6f42825ca47e6e600ddc1fa3e3d663..1c6659f6db420deb9601a48687298a8f05f2340f 100644 --- a/services/appmgr/test/mock/src/cgroup_manager.cpp +++ b/services/appmgr/test/mock/src/cgroup_manager.cpp @@ -27,9 +27,7 @@ namespace OHOS { namespace AppExecFwk { - namespace { - class ScopeGuard final { public: using Function = std::function; @@ -55,7 +53,6 @@ private: Function fn_; bool dismissed_ = false; }; - } // namespace CgroupManager::CgroupManager() : memoryEventControlFd_(-1) @@ -155,6 +152,5 @@ bool CgroupManager::SetFreezerSubsystem(const int tid, const SchedPolicyFreezer APP_LOGD("SetFreezerSubsystem start."); return true; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/test/mock/src/mock_bundle_manager.cpp b/services/appmgr/test/mock/src/mock_bundle_manager.cpp index 7befaaed6dd0913f4ffa442cde57e3ac7b50102b..45668e90e7d5682569532a1fc4e5790968c65442 100644 --- a/services/appmgr/test/mock/src/mock_bundle_manager.cpp +++ b/services/appmgr/test/mock/src/mock_bundle_manager.cpp @@ -21,13 +21,13 @@ namespace OHOS { namespace AppExecFwk { - bool BundleMgrProxy::QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) { ElementName eleName = want.GetElement(); if (eleName.GetBundleName().empty()) { return false; } + abilityInfo.visible = true; abilityInfo.name = eleName.GetAbilityName(); abilityInfo.bundleName = eleName.GetBundleName(); abilityInfo.applicationName = "Helloworld"; @@ -70,6 +70,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(); @@ -135,6 +136,5 @@ bool BundleMgrService::GetBundleGids(const std::string &bundleName, std::vector< gids.push_back(userGid3); return true; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp b/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp index 2d342890cd87dcb3f719c1e5c86f9ab9c5062ae6..ebd54c033cde14ef0ec4eb3277e750978b372441 100644 --- a/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp +++ b/services/appmgr/test/mock/src/sys_mgr_client_mock.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace AppExecFwk { - sptr SysMrgClient::GetSystemAbility(const int32_t systemAbilityId) { if (servicesMap_[systemAbilityId] == nullptr) { @@ -42,6 +41,5 @@ void SysMrgClient::RegisterSystemAbility(const int32_t systemAbilityId, 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_death_recipient_test/ams_app_death_recipient_test.cpp b/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp index 3e5165ba47427e444e5e1cc3b53cda868339e184..7c3e62b0c77af10fb82ea4a4a5e83cbd3a529fc0 100644 --- a/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp +++ b/services/appmgr/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp @@ -33,7 +33,6 @@ using testing::SetArgReferee; namespace OHOS { namespace AppExecFwk { - class AppDeathRecipientTest : public testing::Test { public: static void SetUpTestCase(); @@ -200,6 +199,5 @@ HWTEST_F(AppDeathRecipientTest, AppDeathRecipient_002, TestSize.Level1) EXPECT_EQ(0, static_cast(appDeathRecipientObject_->appMgrServiceInner_.lock()->GetRecentAppList().size())); APP_LOGI("AppDeathRecipient_002 start"); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp index 013644431605d2589218231cdb3fcf84379bbfd0..6b33aab85c7464adc25065dfb7428d24af31bd8e 100644 --- a/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp +++ b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp @@ -198,7 +198,7 @@ std::shared_ptr AmsAppLifeCycleTest::CreateTestApplicationAndS auto appRecord = serviceInner_->GetOrCreateAppRunningRecord(token, appInfo, abilityInfo, "AmsAppLifeCycleTest", 0, result); EXPECT_NE(appRecord, nullptr); - appRecord->SetEventHandler(handler_); + appRecord->SetEventHandler(handler_); EXPECT_EQ(appRecord->GetRecordId(), result.appRecordId); appRecord->SetState(appState); return appRecord; @@ -2026,6 +2026,5 @@ HWTEST_F(AmsAppLifeCycleTest, GetAbilityRunningRecordByAbilityToken_001, TestSiz auto abilityRecord2 = serviceInner_->GetAbilityRunningRecordByAbilityToken(token2); EXPECT_FALSE(abilityRecord2); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp b/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp index ec0b9b17ea8b65efa1e3298c802223aba75bc62b..1b05cbfcb4f817b40eeaad7131da553423f6044f 100644 --- a/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp +++ b/services/appmgr/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp @@ -76,7 +76,6 @@ protected: { return mock_token_; } - protected: std::shared_ptr testAbilityRecord_; sptr client_; @@ -1226,6 +1225,5 @@ HWTEST_F(AmsAppRunningRecordTest, OnAbilityStateChanged_001, TestSize.Level0) appRecord->OnAbilityStateChanged(abilityRecord, AbilityState::ABILITY_STATE_BACKGROUND); EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, abilityRecord->GetState()); } - } // namespace AppExecFwk } // namespace OHOS 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_mgr_scheduler_test/ams_mgr_scheduler_test.cpp b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp index d1568e48e04af9fac982eade0d4ef0fb3fcfc231..fda4e00117fa854dcb99cf60f68ef5eee2addcad 100644 --- a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp +++ b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp @@ -31,14 +31,12 @@ using testing::Return; namespace OHOS { namespace AppExecFwk { - class AmsMgrSchedulerTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); void SetUp(); void TearDown(); - public: protected: static const std::string GetTestAppName() @@ -404,6 +402,5 @@ HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_010, TestSize.Level0) APP_LOGD("AmsMgrScheduler_010 end."); } - } // namespace AppExecFwk } // namespace OHOS 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..5165e060fe443f50c103a5abed5c71584703c6e0 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 @@ -11,17 +25,17 @@ #include #include "lmks_client.h" +namespace{ constexpr int APP_OOM_ADJ_BACKGROUND_MIN = 400; constexpr int APP_OOM_ADJ_SUSPEND_MIN = 600; const std::string APP_RECORD_NAME = "App_Name_Z"; static constexpr int APP_SUSPEND_TIMEOUT_DEFAULT = 100; static constexpr int APP_USLEEP = 200 * 1000; - using namespace testing::ext; +}; namespace OHOS { namespace AppExecFwk { - class AmsProcessOptimizerTest : public testing::Test { public: static void SetUpTestCase(); @@ -887,6 +901,5 @@ HWTEST_F(AmsProcessOptimizerTest, AmsProcessOptimizerTest_StopAppSuspendTimer_00 APP_LOGD("AmsProcessOptimizerTest_StopAppSuspendTimer_001 end."); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file 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..2c9b6be487cd3bff2df35c8984fe3c051597f14c 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)); @@ -409,6 +409,5 @@ HWTEST_F(AmsRecentAppListTest, PushAppFront_001, TestSize.Level1) serviceInner_->PushAppFront(appRecord->GetRecordId()); EXPECT_NE(nullptr, serviceInner_->GetAppTaskInfoById(appRecord->GetRecordId())); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp index 65fd2f308ab0de9b1989520ee00f3e5138ad7bce..ce8d58184893d4da13408007981bb33e96484854 100644 --- a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp @@ -37,6 +37,13 @@ using testing::Return; using testing::SetArgReferee; namespace OHOS { namespace AppExecFwk { +#define CHECK_POINTER_IS_NULLPTR(object) \ + do { \ + if (object == nullptr) { \ + return; \ + } \ + } while (0) + class AmsServiceLoadAbilityProcessTest : public testing::Test { public: static void SetUpTestCase(); @@ -129,12 +136,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_001 end"); } @@ -171,13 +180,15 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = GetMockToken(); @@ -195,10 +206,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) const uint32_t EXPECT_MAP_SIZE = 2; EXPECT_EQ(recordMap.size(), EXPECT_MAP_SIZE); auto record2 = service_->GetAppRunningRecordByAppName(GetTestAppName() + "_1"); - ASSERT_NE(record2, nullptr); + EXPECT_NE(record2, nullptr); + CHECK_POINTER_IS_NULLPTR(record2); EXPECT_EQ(record2->GetState(), ApplicationState::APP_STATE_CREATE); auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityRecord2, nullptr); + EXPECT_NE(abilityRecord2, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord2); EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_002 end"); } @@ -348,12 +361,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_007, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); std::shared_ptr mockClientPtr = std::make_shared(); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); @@ -394,12 +409,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); sptr preToken = token; @@ -418,7 +435,8 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) const auto &abilityMap2 = record2->GetAbilities(); EXPECT_EQ(abilityMap2.size(), EXPECT_MAP_SIZE); auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityRecord2, nullptr); + EXPECT_NE(abilityRecord2, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord2); EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); EXPECT_EQ(abilityRecord2->GetPreToken(), token); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_008 end"); @@ -455,7 +473,8 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetPriorityObject()->GetPid(), PID); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest RequestProcess_001 end"); @@ -582,12 +601,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LaunchMode_001 end"); } @@ -619,12 +640,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); std::shared_ptr mockClientPtr = std::make_shared(); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); @@ -666,12 +689,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -690,7 +715,8 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) const auto &abilityMap1 = record1->GetAbilities(); EXPECT_EQ(abilityMap1.size(), (uint32_t)2); auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityrecord1, nullptr); + EXPECT_NE(abilityrecord1, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityrecord1); EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_001 end"); } @@ -720,12 +746,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -773,12 +801,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_003, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); @@ -825,12 +855,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_004, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); auto abilityInfo2 = std::make_shared(); abilityInfo2->name = GetTestAbilityName() + "_1"; @@ -876,12 +908,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -898,7 +932,8 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) const auto &abilityMap1 = record1->GetAbilities(); EXPECT_EQ(abilityMap1.size(), (uint32_t)2); auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); - ASSERT_NE(abilityrecord1, nullptr); + EXPECT_NE(abilityrecord1, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityrecord1); EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_005 end"); } @@ -928,12 +963,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_006, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); auto abilityInfo2 = std::make_shared(); abilityInfo2->name = GetTestAbilityName() + "_1"; @@ -983,12 +1020,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess001, TestSize.Level1) EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); EXPECT_EQ(record1->GetPriorityObject()->GetPid(), PID); - ASSERT_NE(record1, nullptr); + EXPECT_NE(record1, nullptr); + CHECK_POINTER_IS_NULLPTR(record1); EXPECT_EQ(record1->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record1->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record1->GetAbilityRunningRecordByToken(token); - ASSERT_NE(abilityRecord, nullptr); + EXPECT_NE(abilityRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRecord); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess001 end"); } @@ -1019,7 +1058,8 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record1, nullptr); + EXPECT_NE(record1, nullptr); + CHECK_POINTER_IS_NULLPTR(record1); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess002 end"); } @@ -1050,7 +1090,8 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess003, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); - ASSERT_NE(record1, nullptr); + EXPECT_NE(record1, nullptr); + CHECK_POINTER_IS_NULLPTR(record1); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess003 end"); } @@ -1083,7 +1124,8 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess004, TestSize.Level1) .WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_TIMED_OUT))); std::shared_ptr record = service_->GetOrCreateAppRunningRecord(token, appInfo, abilityInfo, GetTestAppName(), 0, result); - ASSERT_NE(record, nullptr); + EXPECT_NE(record, nullptr); + CHECK_POINTER_IS_NULLPTR(record); service_->StartProcess(abilityInfo->applicationName, GetTestAppName(), record); auto record1 = service_->GetAppRunningRecordByAppRecordId(record->GetRecordId()); EXPECT_EQ(record1, nullptr); diff --git a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp index 5de5eecffcd63f80adef14bcf38a6918746b6f85..c64e01a06e420a78b2fc08384e24548db936da00 100644 --- a/services/appmgr/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp +++ b/services/appmgr/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp @@ -23,22 +23,18 @@ #include #include "mock_app_scheduler.h" #include "inner_event.h" - #include using namespace testing::ext; - namespace OHOS { namespace AppExecFwk { - static bool eventHandlerFlag_ = false; class MockAMSEventHandler : public AMSEventHandler { - public: MockAMSEventHandler(const std::shared_ptr &runner, const std::shared_ptr &ams); virtual ~MockAMSEventHandler(); - virtual void ProcessEvent(const InnerEvent::Pointer &event) override + void ProcessEvent(const InnerEvent::Pointer &event) override { if (event->GetInnerEventId() == 10) { eventHandlerFlag_ = true; @@ -126,15 +122,10 @@ HWTEST_F(AMSEventHandlerTest, app_mgr_service_event_handler_test_001, TestSize.L if (!testAms) { APP_LOGI("app_mgr_service_event_handler_test : testAms is null"); } - EXPECT_FALSE(eventHandler_); - // init eventHandler_ = std::make_shared(runner_, testAms); - EXPECT_TRUE(eventHandler_); - // EXPECT_TRUE(eventHandler_->testAms_); - APP_LOGI("app_mgr_service_event_handler_test end"); } @@ -171,6 +162,6 @@ HWTEST_F(AMSEventHandlerTest, app_mgr_service_event_handler_test_002, TestSize.L APP_LOGI("app_mgr_service_event_handler_test end"); } - } // namespace AppExecFwk + } // namespace OHOS 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_data_storage.h b/services/bundlemgr/include/bundle_data_storage.h index 13a7cf551b4abbcacd7df0586b9ac899e3a5c968..0ced4892e2d0e96812fda805925374524d51df70 100644 --- a/services/bundlemgr/include/bundle_data_storage.h +++ b/services/bundlemgr/include/bundle_data_storage.h @@ -47,7 +47,7 @@ public: */ virtual bool DeleteStorageBundleInfo(const std::string &deviceId, const InnerBundleInfo &innerBundleInfo); - virtual bool ResetKvStore() { return true;} + virtual bool ResetKvStore() { return true; } private: bool KeyToDeviceAndName(const std::string &key, std::string &deviceId, std::string &bundleName) const; void DeviceAndNameToKey(const std::string &deviceId, const std::string &bundleName, std::string &key) const; diff --git a/services/bundlemgr/include/bundle_data_storage_database.h b/services/bundlemgr/include/bundle_data_storage_database.h index 201116725631f48771b7e3297ce1dd6098c91b78..2387d6e10221ce4ee98ca97d79756ef4e2934b00 100644 --- a/services/bundlemgr/include/bundle_data_storage_database.h +++ b/services/bundlemgr/include/bundle_data_storage_database.h @@ -63,8 +63,8 @@ private: DistributedKv::Status GetKvStore(); private: - const DistributedKv::AppId appId_{Constants::APP_ID}; - const DistributedKv::StoreId storeId_{Constants::STORE_ID}; + const DistributedKv::AppId appId_ {Constants::APP_ID}; + const DistributedKv::StoreId storeId_ {Constants::STORE_ID}; bool KeyToDeviceAndName(const std::string &key, std::string &deviceId, std::string &bundleName) const; void DeviceAndNameToKey(const std::string &deviceId, const std::string &bundleName, std::string &key) const; DistributedKv::DistributedKvDataManager dataManager_; 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..e7db5394ebdc1a9a9fd8f90223c6420c5c9fa014 --- /dev/null +++ b/services/bundlemgr/include/bundle_permissions_changed_monitor.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_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_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 90f202b510c4265dc8c04b9dfcaac6495301400e..a5a659e0c8c184b5cccefebdb87b988f22302cea 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"; @@ -117,10 +119,12 @@ const std::string BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN = "when"; const std::string BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN_INUSE = "inuse"; const std::string BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN_ALWAYS = "always"; const std::string BUNDLE_MODULE_PROFILE_KEY_CUSTOMIZE_DATA = "customizeData"; +const std::string BUNDLE_MODULE_PROFILE_KEY_MAIN_ABILITY = "mainAbility"; // sub BUNDLE_MODULE_PROFILE_KEY_DISTRO 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 +194,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"; @@ -209,6 +215,17 @@ const std::string BUNDLE_MODULE_PROFILE_KEY_SHORTCUT_INTENTS = "intents"; const std::string BUNDLE_MODULE_PROFILE_KEY_TARGET_CLASS = "targetClass"; const std::string BUNDLE_MODULE_PROFILE_KEY_TARGET_BUNDLE = "targetBundle"; +const uint32_t VALUE_HOME_SCREEN = 1 << 0; +// 000010 represents supporting search box +const uint32_t VALUE_SEARCHBOX = 1 << 1; + +const std::string KEY_HOME_SCREEN = "homeScreen"; +const std::string KEY_SEARCHBOX = "searchbox"; + +const std::string BUNDLE_MODULE_PROFILE_KEY_JS_TYPE_ETS = "ets"; + +static std::map formEntityMap; + extern thread_local int32_t parseResult; } // namespace ProfileReader diff --git a/services/bundlemgr/include/inner_bundle_info.h b/services/bundlemgr/include/inner_bundle_info.h index f67d5e15d5b8a1b83951da06e60eab534f968298..de34790d82805efa7ae94db9efd6427d3ec3ebcf 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,13 @@ 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; + std::string mainAbility; bool isEntry; + bool installationFree; MetaData metaData; ModuleColorMode colorMode = ModuleColorMode::AUTO; Distro distro; @@ -119,7 +125,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 +136,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 +148,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; @@ -290,6 +296,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 +334,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 +560,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; } } @@ -875,12 +893,12 @@ public: void SetProvisionId(const std::string &provisionId) { - provisionId_ = provisionId; + baseBundleInfo_.appId = baseBundleInfo_.name + Constants::FILE_UNDERLINE + provisionId; } std::string GetProvisionId() const { - return provisionId_; + return baseBundleInfo_.appId; } void SetAppFeature(const std::string &appFeature) @@ -918,19 +936,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) { @@ -966,21 +984,26 @@ public: */ bool CheckSpecialMetaData(const std::string &metaData) const; /** - * @brief Obtains the FormInfo objects provided by all applications on the device. + * @brief Obtains the FormInfo objects provided by all applications on the device. * @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; @@ -994,14 +1017,13 @@ private: ApplicationInfo baseApplicationInfo_; BundleInfo baseBundleInfo_; // applicationInfo and abilityInfo empty std::string mainAbility_; - std::string provisionId_; std::string appFeature_; bool hasEntry_ = false; // only using for install or update progress, doesn't need to save to database 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 61f3a1831a38e8043bb42f1b5ad3a60416c6059d..f0e0dcc058cd261e857288fc0fbdc9c798dd68e3 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,10 +199,6 @@ ErrCode BaseBundleInstaller::ProcessBundleInstall( newInfo.SetAppType(appType); newInfo.SetUserId(installParam.userId); newInfo.SetIsKeepData(installParam.isKeepData); - auto provisionInfo = hapVerifyResult.GetProvisionInfo(); - newInfo.SetProvisionId(provisionInfo.appId); - newInfo.SetAppFeature(provisionInfo.bundleInfo.appFeature); - if (!ModifyInstallDirByHapType(newInfo)) { APP_LOGE("modify bundle install dir failed %{public}d", result); return ERR_APPEXECFWK_INSTALL_PARAM_ERROR; @@ -203,6 +208,11 @@ ErrCode BaseBundleInstaller::ProcessBundleInstall( APP_LOGE("bundle parse failed %{public}d", result); return result; } + if (installParam.noCheckSignature == false) { + auto provisionInfo = hapVerifyResult.GetProvisionInfo(); + newInfo.SetProvisionId(provisionInfo.appId); + newInfo.SetAppFeature(provisionInfo.bundleInfo.appFeature); + } UpdateInstallerState(InstallerState::INSTALL_PARSED); bundleName_ = newInfo.GetBundleName(); @@ -221,17 +231,19 @@ ErrCode BaseBundleInstaller::ProcessBundleInstall( return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR; } auto &mtx = dataMgr_->GetBundleMutex(bundleName_); - std::lock_guard lock{mtx}; + std::lock_guard lock {mtx}; 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"); @@ -248,12 +260,13 @@ ErrCode BaseBundleInstaller::ProcessBundleUninstall(const std::string &bundleNam return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR; } auto &mtx = dataMgr_->GetBundleMutex(bundleName); - std::lock_guard lock{mtx}; + std::lock_guard lock {mtx}; InnerBundleInfo oldInfo; if (!dataMgr_->GetInnerBundleInfo(bundleName, Constants::CURRENT_DEVICE_ID, oldInfo)) { 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"); @@ -282,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"); @@ -299,12 +312,13 @@ ErrCode BaseBundleInstaller::ProcessBundleUninstall( return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR; } auto &mtx = dataMgr_->GetBundleMutex(bundleName); - std::lock_guard lock{mtx}; + std::lock_guard lock {mtx}; InnerBundleInfo oldInfo; if (!dataMgr_->GetInnerBundleInfo(bundleName, Constants::CURRENT_DEVICE_ID, oldInfo)) { 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) { @@ -368,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)) { @@ -381,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); }); @@ -685,7 +700,7 @@ bool BaseBundleInstaller::ModifyInstallDirByHapType(InnerBundleInfo &info) bool BaseBundleInstaller::UpdateBundlePaths(InnerBundleInfo &info, const std::string baseDataPath) const { info.SetBaseDataDir(baseDataPath); - info.SetAppDataDir(baseDataPath + Constants::PATH_SEPARATOR + Constants::DATA_DIR); + info.SetAppDataDir(baseDataPath); info.SetAppDataBaseDir(baseDataPath + Constants::PATH_SEPARATOR + Constants::DATA_BASE_DIR); info.SetAppCacheDir(baseDataPath + Constants::PATH_SEPARATOR + Constants::CACHE_DIR); return true; diff --git a/services/bundlemgr/src/bundle_data_mgr.cpp b/services/bundlemgr/src/bundle_data_mgr.cpp index 53268c42bb9572e865561b664ace88e591c35e48..9c080158d998dc21107c4d827a0db0d336cd9308 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; } @@ -683,8 +751,8 @@ bool BundleDataMgr::GetLaunchWantForBundle(const std::string &bundleName, Want & bool BundleDataMgr::CheckIsSystemAppByUid(const int uid) const { - int maxSysUid{Constants::MAX_SYS_UID}; - int baseSysUid{Constants::ROOT_UID}; + int maxSysUid {Constants::MAX_SYS_UID}; + int baseSysUid {Constants::ROOT_UID}; if (uid >= baseSysUid && uid <= maxSysUid) { return true; } @@ -1017,8 +1085,9 @@ bool BundleDataMgr::GenerateUidAndGid(InnerBundleInfo &info) APP_LOGI("the %{public}d app install", i); innerMap.emplace(i, info.GetBundleName()); uid = i + baseUid; - info.SetUid(baseUid); - info.SetGid(baseUid); + APP_LOGI("the uid is %{public}d", uid); + info.SetUid(uid); + info.SetGid(uid); return true; } } @@ -1053,8 +1122,10 @@ bool BundleDataMgr::RecycleUidAndGid(const InnerBundleInfo &info) return (appUidMap_); } }(); + std::lock_guard lock(uidMapMutex_); for (auto &kv : innerMap) { if (kv.second == info.GetBundleName()) { + APP_LOGI("the recycle uid is %{public}d", kv.first); innerMap.erase(kv.first); return true; } @@ -1062,6 +1133,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 @@ -1069,10 +1201,13 @@ bool BundleDataMgr::RestoreUidAndGid() for (const auto &info : item.second) { uint32_t uid = info.second.GetUid(); if ((uid < Constants::BASE_SYS_VEN_UID) && (uid >= Constants::BASE_SYS_UID)) { + std::lock_guard lock(uidMapMutex_); sysUidMap_[uid - Constants::BASE_SYS_UID] = info.second.GetBundleName(); } else if ((uid >= Constants::BASE_SYS_VEN_UID) && (uid <= Constants::MAX_SYS_VEN_UID)) { + std::lock_guard lock(uidMapMutex_); sysVendorUidMap_[uid - Constants::BASE_SYS_VEN_UID] = info.second.GetBundleName(); } else if (uid > Constants::MAX_SYS_VEN_UID) { + std::lock_guard lock(uidMapMutex_); appUidMap_[uid - Constants::BASE_APP_UID] = info.second.GetBundleName(); } } @@ -1081,7 +1216,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,7 +1265,9 @@ bool BundleDataMgr::NotifyBundleStatus(const std::string &bundleName, const std: element.SetBundleName(bundleName); element.SetAbilityName(mainAbility); want.SetElement(element); - EventFwk::CommonEventData commonData{want}; + want.SetParam(Constants::UID, uid); + APP_LOGI("want.SetParam uid %{public}d", uid); + EventFwk::CommonEventData commonData {want}; EventFwk::CommonEventManager::PublishCommonEvent(commonData); return true; } @@ -1141,7 +1278,7 @@ std::mutex &BundleDataMgr::GetBundleMutex(const std::string &bundleName) auto it = bundleMutexMap_.find(bundleName); if (it == bundleMutexMap_.end()) { bundleMutex_.unlock_shared(); - std::unique_lock lock{bundleMutex_}; + std::unique_lock lock {bundleMutex_}; return bundleMutexMap_[bundleName]; } bundleMutex_.unlock_shared(); @@ -1315,6 +1452,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 +1549,165 @@ 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 allPermissionsItem = allPermissionsCallbacks_.begin(); + allPermissionsItem != allPermissionsCallbacks_.end();) { + if ((*allPermissionsItem)->AsObject() == callback->AsObject()) { + allPermissionsItem = allPermissionsCallbacks_.erase(allPermissionsItem); + APP_LOGI("unregister from all permissions callbacks success!"); + ret = true; + break; + } else { + allPermissionsItem++; + } + } + } + { + 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 &allPermissionItem : allPermissionsCallbacks_) { + if (!allPermissionItem) { + APP_LOGE("callback is nullptr"); + return false; + } + + allPermissionItem->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..de0ec698cb3a8a333b6266321e0687fcbaba451f 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() @@ -111,10 +112,6 @@ void BundleDataStorageDatabase::SaveEntries( allDevicesInfos.emplace(deviceId, innerBundleInfo); infos.emplace(bundleName, allDevicesInfos); } - - // don't care result, must be right - // Security::Permission::PermissionKit permissionKit; - // permissionKit.RestoreAppPermissions(innerBundleInfo->GetAppPermissionInfo()); } APP_LOGD("SaveEntries end"); } @@ -142,7 +139,6 @@ bool BundleDataStorageDatabase::LoadAllData(std::mapGetBundleName(), status); APP_LOGE("put valLocalAbilityManager::InitializeSaProfilesue to kvStore error: %{public}d", status); return false; } else { @@ -213,11 +207,8 @@ bool BundleDataStorageDatabase::DeleteStorageBundleInfo( } } - // ProfileManager::GetInstance().ChangeDatasToProfile(data, ProfileManager::DELETE_DATAS_FROM_PROFILE, 0); - if (status != Status::SUCCESS) { const std::string interfaceName = "kvStorePtr::Delete()"; - // SendEvent(interfaceName, data->GetBundleName(), status); APP_LOGE("delete key error: %{public}d", status); return false; } else { @@ -255,7 +246,11 @@ Status BundleDataStorageDatabase::GetKvStore() { Status status; Options options = { - .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION}; + .createIfMissing = true, + .encrypt = false, + .autoSync = true, + .kvStoreType = KvStoreType::SINGLE_VERSION + }; dataManager_.GetSingleKvStore( options, appId_, storeId_, [this, &status](Status paramStatus, std::unique_ptr singleKvStore) { @@ -309,4 +304,4 @@ bool BundleDataStorageDatabase::ResetKvStore() } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/src/bundle_mgr_host_impl.cpp b/services/bundlemgr/src/bundle_mgr_host_impl.cpp index 7d9a94cda75983db6aa7f32a7cf78b7212495f03..03c8fed2c3cc9f33bea72200778eb9621db9807f 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_profile.cpp b/services/bundlemgr/src/bundle_profile.cpp index 27611f30615555d86795dee69f77149f77c9e24a..472576be4ba1a9e5796689adb9859ae812c221e4 100644 --- a/services/bundlemgr/src/bundle_profile.cpp +++ b/services/bundlemgr/src/bundle_profile.cpp @@ -29,23 +29,42 @@ namespace ProfileReader { thread_local int32_t parseResult; const std::map ABILITY_TYPE_MAP = { - {"page", AbilityType::PAGE}, {"service", AbilityType::SERVICE}, {"data", AbilityType::DATA}}; + {"page", AbilityType::PAGE}, + {"service", AbilityType::SERVICE}, + {"data", AbilityType::DATA}, + {"form", AbilityType::FORM} +}; const std::map DISPLAY_ORIENTATION_MAP = { {"unspecified", DisplayOrientation::UNSPECIFIED}, {"landscape", DisplayOrientation::LANDSCAPE}, {"portrait", DisplayOrientation::PORTRAIT}, - {"followrecent", DisplayOrientation::FOLLOWRECENT}}; + {"followrecent", DisplayOrientation::FOLLOWRECENT} +}; const std::map LAUNCH_MODE_MAP = { - {"singleton", LaunchMode::SINGLETON}, {"singletop", LaunchMode::SINGLETOP}, {"standard", LaunchMode::STANDARD}}; -const std::map dimensionMap = {{"1*2", 1}, {"2*2", 2}, {"2*4", 3}, {"4*4", 4}}; -const std::map formTypeMap = {{"JS", FormType::JS}, {"Java", FormType::JAVA}}; + {"singleton", LaunchMode::SINGLETON}, + {"singletop", LaunchMode::SINGLETOP}, + {"standard", LaunchMode::STANDARD} +}; +const std::map dimensionMap = { + {"1*2", 1}, + {"2*2", 2}, + {"2*4", 3}, + {"4*4", 4} +}; +const std::map formTypeMap = { + {"JS", FormType::JS}, + {"Java", FormType::JAVA} +}; const std::map moduleColorMode = { {"auto", ModuleColorMode::AUTO}, {"dark", ModuleColorMode::DARK}, {"light", ModuleColorMode::LIGHT}, }; const std::map formColorModeMap = { - {"auto", FormsColorMode::AUTO_MODE}, {"dark", FormsColorMode::DARK_MODE}, {"light", FormsColorMode::LIGHT_MODE}}; + {"auto", FormsColorMode::AUTO_MODE}, + {"dark", FormsColorMode::DARK_MODE}, + {"light", FormsColorMode::LIGHT_MODE} +}; struct Version { int32_t code = 0; @@ -149,6 +168,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 +195,7 @@ struct CustomizeData { struct MetaData { std::vector parameters; std::vector results; - std::vector customizeData; + std::vector customizeData; }; struct UriPermission { @@ -201,6 +222,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 +279,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; @@ -268,6 +292,7 @@ struct Module { std::vector shortcuts; std::vector defPermissions; std::vector reqPermissions; + std::string mainAbility; }; // config.json @@ -789,7 +814,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 +1001,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 +1078,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 +1566,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, @@ -1581,6 +1646,14 @@ void from_json(const nlohmann::json &jsonObject, Module &module) false, parseResult, ArrayType::OBJECT); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + BUNDLE_MODULE_PROFILE_KEY_MAIN_ABILITY, + module.mainAbility, + JsonType::STRING, + false, + parseResult, + ArrayType::NOT_ARRAY); } void from_json(const nlohmann::json &jsonObject, ConfigJson &configJson) @@ -1686,13 +1759,29 @@ bool CheckModuleInfosIsValid(ProfileReader::ConfigJson &configJson) } return true; } +uint32_t GetFormEntity(const std::vector &formEntity) +{ + if (ProfileReader::formEntityMap.empty()) { + ProfileReader::formEntityMap.insert({ProfileReader::KEY_HOME_SCREEN, ProfileReader::VALUE_HOME_SCREEN}); + ProfileReader::formEntityMap.insert({ProfileReader::KEY_SEARCHBOX, ProfileReader::VALUE_SEARCHBOX}); + } + + uint32_t formEntityInBinary = 0; + for (const auto &item : formEntity) { + if (ProfileReader::formEntityMap.find(item) != ProfileReader::formEntityMap.end()) { + formEntityInBinary |= ProfileReader::formEntityMap[item]; + } + } + return formEntityInBinary; +} 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), @@ -1711,13 +1800,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; }); @@ -1785,21 +1874,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; @@ -1813,6 +1902,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; }); @@ -1824,6 +1914,7 @@ bool TransformToInfo(const ProfileReader::ConfigJson &configJson, InnerModuleInf innerModuleInfo.reqCapabilities = configJson.module.reqCapabilities; innerModuleInfo.defPermissions = configJson.module.defPermissions; innerModuleInfo.reqPermissions = configJson.module.reqPermissions; + innerModuleInfo.mainAbility = configJson.module.mainAbility; return true; } @@ -1831,11 +1922,25 @@ 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; + std::transform( + abilityInfo.srcLanguage.begin(), abilityInfo.srcLanguage.end(), abilityInfo.srcLanguage.begin(), ::tolower); + if (abilityInfo.srcLanguage != ProfileReader::BUNDLE_MODULE_PROFILE_KEY_JS && + abilityInfo.srcLanguage != ProfileReader::BUNDLE_MODULE_PROFILE_KEY_JS_TYPE_ETS) { + abilityInfo.isNativeAbility = true; + } 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; }); @@ -1866,6 +1971,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; @@ -1873,14 +1982,17 @@ 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.formEntity = ability.form.formEntity; + abilityInfo.configChanges = ability.configChanges; + abilityInfo.formEntity = GetFormEntity(ability.form.formEntity); abilityInfo.minFormHeight = ability.form.minHeight; abilityInfo.defaultFormHeight = ability.form.defaultHeight; abilityInfo.minFormWidth = ability.form.minWidth; abilityInfo.defaultFormWidth = ability.form.defaultWidth; GetMetaData(abilityInfo.metaData, ability.metaData); + abilityInfo.formEnabled = ability.formsEnabled; return true; } @@ -1935,6 +2047,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; @@ -1951,6 +2066,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; @@ -1958,6 +2076,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) != @@ -1969,7 +2091,6 @@ bool TransformToInfo(ProfileReader::ConfigJson &configJson, InnerBundleInfo &inn } if (configJson.module.jses.empty()) { bundleInfo.isNativeApp = true; - abilityInfo.isNativeAbility = true; } innerBundleInfo.InsertAbilitiesInfo(keyName, abilityInfo); } diff --git a/services/bundlemgr/src/bundle_util.cpp b/services/bundlemgr/src/bundle_util.cpp index 9dd08b4590d02aa9e53fd805bb1831cd5b0d32cc..e9e2476ed19781c3983086a87291b41ad52a9888 100644 --- a/services/bundlemgr/src/bundle_util.cpp +++ b/services/bundlemgr/src/bundle_util.cpp @@ -44,7 +44,7 @@ ErrCode BundleUtil::CheckFilePath(const std::string &bundlePath, std::string &re APP_LOGE("can not access the bundle file path: %{private}s", realPath.c_str()); return ERR_APPEXECFWK_INSTALL_INVALID_BUNDLE_FILE; } - if(!CheckFileSize(realPath, Constants::MAX_HAP_SIZE)) { + if (!CheckFileSize(realPath, Constants::MAX_HAP_SIZE)) { APP_LOGE("file size is larger than max size Max size is: %{public}d", Constants::MAX_HAP_SIZE); return ERR_APPEXECFWK_INSTALL_INVALID_HAP_SIZE; } @@ -84,10 +84,10 @@ bool BundleUtil::CheckFileName(const std::string &fileName) bool BundleUtil::CheckFileSize(const std::string &bundlePath, const int32_t fileSize) { struct stat fileInfo = { 0 }; - if (stat(bundlePath.c_str(), &fileInfo) != 0) { + if (stat(bundlePath.c_str(), &fileInfo) != 0) { APP_LOGE("call stat error"); - return false; - } + return false; + } if (fileInfo.st_size > fileSize) { return false; } diff --git a/services/bundlemgr/src/inner_bundle_info.cpp b/services/bundlemgr/src/inner_bundle_info.cpp index f523b5371db717647f79a0c7a41f20255a9b6c24..787ac25d6e5ad26d3df720fea6843ff340106efa 100644 --- a/services/bundlemgr/src/inner_bundle_info.cpp +++ b/services/bundlemgr/src/inner_bundle_info.cpp @@ -35,13 +35,16 @@ const std::string MAIN_ABILITY = "mainAbility"; const std::string SKILL_INFOS = "skillInfos"; const std::string USER_ID = "userId_"; const std::string IS_KEEP_DATA = "isKeepData"; -const std::string PROVISION_ID = "provisionId"; const std::string APP_FEATURE = "appFeature"; const std::string HAS_ENTRY = "hasEntry"; 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"; @@ -55,6 +58,7 @@ const std::string MODULE_ABILITY_KEYS = "abilityKeys"; const std::string MODULE_SKILL_KEYS = "skillKeys"; const std::string MODULE_FORMS = "formInfos"; const std::string MODULE_SHORTCUT = "shortcutInfos"; +const std::string MODULE_MAIN_ABILITY = "mainAbility"; } // namespace @@ -68,20 +72,19 @@ InnerBundleInfo::~InnerBundleInfo() APP_LOGD("inner bundle info instance is destroyed"); } - - void to_json(nlohmann::json &jsonObject, const Distro &distro) { - jsonObject = nlohmann::json{ + 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} }; } void to_json(nlohmann::json &jsonObject, const UsedScene &usedScene) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_ABILITY, usedScene.ability}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN, usedScene.when} }; @@ -89,7 +92,7 @@ void to_json(nlohmann::json &jsonObject, const UsedScene &usedScene) void to_json(nlohmann::json &jsonObject, const ReqPermission &reqPermission) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_NAME, reqPermission.name}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_REASON, reqPermission.reason}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_USEDSCENE, reqPermission.usedScene} @@ -98,7 +101,7 @@ void to_json(nlohmann::json &jsonObject, const ReqPermission &reqPermission) void to_json(nlohmann::json &jsonObject, const DefPermission &defPermission) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_NAME, defPermission.name}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_GRANTMODE, defPermission.grantMode}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE, defPermission.availableScope}, @@ -111,7 +114,7 @@ void to_json(nlohmann::json &jsonObject, const DefPermission &defPermission) void to_json(nlohmann::json &jsonObject, const InnerModuleInfo &info) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {MODULE_PACKAGE, info.modulePackage}, {MODULE_NAME, info.moduleName}, {MODULE_PATH, info.modulePath}, @@ -122,17 +125,22 @@ 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}, {MODULE_ABILITY_KEYS, info.abilityKeys}, - {MODULE_SKILL_KEYS, info.skillKeys} + {MODULE_SKILL_KEYS, info.skillKeys}, + {MODULE_MAIN_ABILITY, info.mainAbility} }; } void to_json(nlohmann::json &jsonObject, const SkillUri &uri) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_SCHEME, uri.scheme}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_HOST, uri.host}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_PORT, uri.port}, @@ -143,7 +151,7 @@ void to_json(nlohmann::json &jsonObject, const SkillUri &uri) void to_json(nlohmann::json &jsonObject, const Skill &skill) { - jsonObject = nlohmann::json{ + jsonObject = nlohmann::json { {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ACTIONS, skill.actions}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ENTITIES, skill.entities}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_URIS, skill.uris} @@ -166,10 +174,9 @@ void InnerBundleInfo::ToJson(nlohmann::json &jsonObject) const jsonObject[IS_KEEP_DATA] = isKeepData_; jsonObject[USER_ID] = userId_; jsonObject[MAIN_ABILITY] = mainAbility_; - jsonObject[PROVISION_ID] = provisionId_; jsonObject[APP_FEATURE] = appFeature_; jsonObject[HAS_ENTRY] = hasEntry_; - jsonObject[MODULE_FORMS] = formInfos_; + jsonObject[MODULE_FORMS] = formInfos_; jsonObject[MODULE_SHORTCUT] = shortcutInfos_; } @@ -257,6 +264,46 @@ 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_MAIN_ABILITY, + info.mainAbility, + JsonType::STRING, + 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, @@ -376,8 +423,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(); @@ -405,6 +450,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) @@ -633,14 +687,6 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey(jsonObject, - jsonObjectEnd, - PROVISION_ID, - provisionId_, - JsonType::STRING, - true, - ProfileReader::parseResult, - ArrayType::NOT_ARRAY); GetValueIfFindKey(jsonObject, jsonObjectEnd, APP_FEATURE, @@ -649,7 +695,7 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey>>(jsonObject, + GetValueIfFindKey>>(jsonObject, jsonObjectEnd, MODULE_FORMS, formInfos_, @@ -657,7 +703,7 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey>(jsonObject, + GetValueIfFindKey>(jsonObject, jsonObjectEnd, MODULE_SHORTCUT, shortcutInfos_, @@ -706,6 +752,7 @@ std::optional InnerBundleInfo::FindHapModuleInfo(const std::strin hapInfo.supportedModes = baseApplicationInfo_.supportedModes; hapInfo.reqCapabilities = it->second.reqCapabilities; hapInfo.colorMode = it->second.colorMode; + hapInfo.mainAbility = it->second.mainAbility; bool first = false; for (auto &ability : baseAbilityInfos_) { if (ability.first.find(modulePackage) != std::string::npos) { @@ -733,6 +780,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()) { @@ -792,7 +859,11 @@ void InnerBundleInfo::UpdateModuleInfo(const InnerBundleInfo &newInfo) } } for (auto it = shortcutInfos_.begin(); it != shortcutInfos_.end();) { - (it->first.find(newInfo.currentPackage_) != std::string::npos) ? shortcutInfos_.erase(it++) : (++it); + if (it->first.find(newInfo.currentPackage_) != std::string::npos) { + shortcutInfos_.erase(it++); + } else { + ++it; + } } if (!hasEntry_ && newInfo.HasEntry()) { hasEntry_ = true; @@ -817,19 +888,39 @@ void InnerBundleInfo::RemoveModuleInfo(const std::string &modulePackage) mainAbility_.clear(); } for (auto it = innerModuleInfos_.begin(); it != innerModuleInfos_.end();) { - (it->first == modulePackage) ? innerModuleInfos_.erase(it++) : (++it); + if (it->first == modulePackage) { + innerModuleInfos_.erase(it++); + } else { + ++it; + } } for (auto it = baseAbilityInfos_.begin(); it != baseAbilityInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? baseAbilityInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + baseAbilityInfos_.erase(it++); + } else { + ++it; + } } for (auto it = skillInfos_.begin(); it != skillInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? skillInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + skillInfos_.erase(it++); + } else { + ++it; + } } for (auto it = formInfos_.begin(); it != formInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? formInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + formInfos_.erase(it++); + } else { + ++it; + } } for (auto it = shortcutInfos_.begin(); it != shortcutInfos_.end();) { - (it->first.find(modulePackage) != std::string::npos) ? shortcutInfos_.erase(it++) : (++it); + if (it->first.find(modulePackage) != std::string::npos) { + shortcutInfos_.erase(it++); + } else { + ++it; + } } } @@ -851,7 +942,6 @@ std::string InnerBundleInfo::ToString() const j[USER_ID] = userId_; j[MAIN_ABILITY] = mainAbility_; j[APP_FEATURE] = appFeature_; - j[PROVISION_ID] = provisionId_; j[HAS_ENTRY] = hasEntry_; j[MODULE_FORMS] = formInfos_; j[MODULE_SHORTCUT] = shortcutInfos_; @@ -893,10 +983,16 @@ void InnerBundleInfo::GetBundleInfo(const BundleFlag flag, BundleInfo &bundleInf std::back_inserter(bundleInfo.defPermissions), [](const auto &p) { return p.name; }); bundleInfo.hapModuleNames.emplace_back(info.second.modulePackage); - bundleInfo.moduleNames.emplace_back(info.second.moduleName); - bundleInfo.moduleDirs.emplace_back(info.second.modulePath); - bundleInfo.modulePublicDirs.emplace_back(info.second.moduleDataDir); - bundleInfo.moduleResPaths.emplace_back(info.second.moduleResPath); + auto hapmoduleinfo = FindHapModuleInfo(info.second.modulePackage); + if (hapmoduleinfo) { + bundleInfo.hapModuleInfos.emplace_back(*hapmoduleinfo); + bundleInfo.moduleNames.emplace_back(info.second.moduleName); + bundleInfo.moduleDirs.emplace_back(info.second.modulePath); + bundleInfo.modulePublicDirs.emplace_back(info.second.moduleDataDir); + bundleInfo.moduleResPaths.emplace_back(info.second.moduleResPath); + } else { + APP_LOGE("can not find hapmoduleinfo %{public}s", info.second.moduleName.c_str()); + } if (info.second.isEntry) { bundleInfo.mainEntry = info.second.modulePackage; bundleInfo.entryModuleName = info.second.moduleName; @@ -927,29 +1023,46 @@ bool InnerBundleInfo::CheckSpecialMetaData(const std::string &metaData) const void InnerBundleInfo::GetFormsInfoByModule(const std::string &moduleName, std::vector &formInfos) const { - for (const auto &data : formInfos_) { - for (auto &form : data.second) { - if (form.moduleName == moduleName) { - formInfos.emplace_back(form); - } - } - } + for (const auto &data : formInfos_) { + for (auto &form : data.second) { + if (form.moduleName == moduleName) { + formInfos.emplace_back(form); + } + } + } } void InnerBundleInfo::GetFormsInfoByApp(std::vector &formInfos) const { - for (const auto &data : formInfos_) { - for (auto &form : data.second) { - formInfos.emplace_back(form); - } - } + for (const auto &data : formInfos_) { + for (auto &form : data.second) { + formInfos.emplace_back(form); + } + } } void InnerBundleInfo::GetShortcutInfos(std::vector &shortcutInfos) const { for (const auto &shortcut : shortcutInfos_) { - shortcutInfos.emplace_back(shortcut.second); - } + shortcutInfos.emplace_back(shortcut.second); + } +} + +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 diff --git a/services/bundlemgr/src/kvstore_death_recipient_callback.cpp b/services/bundlemgr/src/kvstore_death_recipient_callback.cpp index 3b1eb834f4b88b23da6b25156fb37dd1cb254896..92d4f9de455a653d45ac54ae0f3a4c17da60c21e 100644 --- a/services/bundlemgr/src/kvstore_death_recipient_callback.cpp +++ b/services/bundlemgr/src/kvstore_death_recipient_callback.cpp @@ -27,9 +27,9 @@ namespace AppExecFwk { namespace { const int32_t CHECK_TIMES = 300; -const int32_t CHECK_INTERVAL = 100000; // 100ms +const int32_t CHECK_INTERVAL = 100000; // 100ms -} // namespace +} // namespace KvStoreDeathRecipientCallback::KvStoreDeathRecipientCallback() { @@ -63,13 +63,7 @@ void KvStoreDeathRecipientCallback::OnRemoteDied() // init kvStore. if (dataStorage && dataStorage->ResetKvStore()) { // register data change listener again. - //dataStorage->RegisterChangeListener(); APP_LOGI("current times is %{public}d", times); - // auto service = DelayedSingleton::GetInstance(); - // std::shared_ptr handler = service->GetEventHandler(); - // if (handler != nullptr) { - // handler->SendEvent(BMSEventHandler::BUNDLE_SCAN_START); - // } break; } usleep(CHECK_INTERVAL); @@ -79,5 +73,5 @@ void KvStoreDeathRecipientCallback::OnRemoteDied() APP_LOGI("OnRemoteDied, register data change listener end"); } -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file 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..060cea445140c4de2ed79e19ed2d8d66fe6813fe --- /dev/null +++ b/services/bundlemgr/src/module_usage_data_storage.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 "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 = 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 c2a9745cb9671a682e2d37438328e635eaf89d62..eddeb1af06a83c73a6e17f950e4623f35dc2b6fe 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 @@ -30,7 +30,7 @@ using namespace OHOS::AppExecFwk; using namespace OHOS::AppExecFwk::JsonConstants; namespace { -const std::string NORMAL_BUNDLE_NAME{"com.example.test"}; +const std::string NORMAL_BUNDLE_NAME {"com.example.test"}; } // namespace class BmsBundleDataStorageDatabaseTest : public testing::Test { @@ -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": { @@ -142,7 +148,7 @@ protected: }, "baseBundleInfo": { "abilityInfos": [], - "appId": "", + "appId": "BNtg4JBClbl92Rgc3jm/RfcAdrHXaM8F0QOiwVEhnV5ebE5jNIYnAx+weFRT3QTyUjRNdhmc2aAzWyi+5t5CoBM=", "applicationInfo": { "bundleName": "", "cacheDir": "", @@ -238,7 +244,6 @@ protected: "isKeepData": false, "isSupportBackup": false, "mainAbility": "com.ohos.launchercom.ohos.launchercom.ohos.launcher.MainAbility", - "provisionId": "BNtg4JBClbl92Rgc3jm/RfcAdrHXaM8F0QOiwVEhnV5ebE5jNIYnAx+weFRT3QTyUjRNdhmc2aAzWyi+5t5CoBM=", "skillInfos": { "com.ohos.launchercom.ohos.launchercom.ohos.launcher.MainAbility": [ { @@ -287,10 +292,29 @@ protected: "name": "originWidgetName", "value": "com.weather.testWidget" } - ] + ] } ] }, + "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 } @@ -348,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() @@ -384,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()); } /** @@ -427,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()); } /** @@ -480,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()); } /** @@ -522,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()); } /** @@ -534,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 0d62478134192dd3eb575e362c9cafd64dd5f7ee..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 @@ -122,7 +122,7 @@ protected: }, "baseBundleInfo": { "abilityInfos": [], - "appId": "", + "appId": "BNtg4JBClbl92Rgc3jm/RfcAdrHXaM8F0QOiwVEhnV5ebE5jNIYnAx+weFRT3QTyUjRNdhmc2aAzWyi+5t5CoBM=", "applicationInfo": { "bundleName": "", "cacheDir": "", @@ -217,7 +217,6 @@ protected: "isKeepData": false, "isSupportBackup": false, "mainAbility": "com.ohos.launchercom.ohos.launchercom.ohos.launcher.MainAbility", - "provisionId": "BNtg4JBClbl92Rgc3jm/RfcAdrHXaM8F0QOiwVEhnV5ebE5jNIYnAx+weFRT3QTyUjRNdhmc2aAzWyi+5t5CoBM=", "skillInfos": { "com.ohos.launchercom.ohos.launchercom.ohos.launcher.MainAbility": [ { @@ -261,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 @@ -318,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() @@ -367,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()); } /** @@ -410,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()); } /** @@ -463,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()); } /** @@ -505,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()); } /** @@ -572,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()); } /** @@ -595,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); @@ -609,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()); } } @@ -632,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); } @@ -648,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)); } /** @@ -659,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 78b57c41d48b5f1223d17a92651ab870bb403414..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,11 +20,13 @@ 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", "${innerkits_path}/appexecfwk_base/src/bundle_info.cpp", + "${innerkits_path}/appexecfwk_base/src/compatible_ability_info.cpp", + "${innerkits_path}/appexecfwk_base/src/compatible_application_info.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", @@ -35,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 += [ @@ -61,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 7e7a0c352e3bc996e117231e713e8d7da0f52136..967887d6b1dfea068c02e60ccc36ed2ebc269157 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"; @@ -70,7 +75,8 @@ const std::string TARGET_ABILITY = "MockTargetAbility"; const AbilityType ABILITY_TYPE = AbilityType::PAGE; const DisplayOrientation ORIENTATION = DisplayOrientation::PORTRAIT; const LaunchMode LAUNCH_MODE = LaunchMode::SINGLETON; -const std::vector FORM_ENTITY = {"homeScreen","searchbox"}; +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,6 +132,7 @@ 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 @@ -136,6 +144,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; @@ -153,6 +163,10 @@ public: const std::string &bundleName, const uint32_t permissionSize, const ApplicationInfo &appInfo) const; void CheckAbilityInfo( const std::string &bundleName, const std::string &abilityName, const AbilityInfo &appInfo) const; + void CheckCompatibleApplicationInfo( + const std::string &bundleName, const uint32_t permissionSize, const CompatibleApplicationInfo &appInfo) const; + void CheckCompatibleAbilityInfo( + const std::string &bundleName, const std::string &abilityName, const CompatibleAbilityInfo &appInfo) const; void CheckInstalledBundleInfos(const uint32_t abilitySize, const std::vector &bundleInfos) const; void CheckInstalledApplicationInfos(const uint32_t permsSize, const std::vector &appInfos) const; void CheckModuleInfo(const HapModuleInfo &hapModuleInfo) const; @@ -228,14 +242,30 @@ 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; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; FormInfo form = MockFormInfo(bundleName, moduleName, abilityName); @@ -248,8 +278,15 @@ void BmsBundleKitServiceTest::MockInstallBundle( innerBundleInfo.SetUid((bundleName == BUNDLE_NAME_TEST) ? TEST_UID : DEMO_UID); // for launch ability if (bundleName == BUNDLE_NAME_TEST) { - AppExecFwk::SkillUri uri{URI_SCHEME, URI_HOST}; - Skill skill{{ACTION}, {ENTITY}, {uri}}; + AppExecFwk::SkillUri uri { + URI_SCHEME, + URI_HOST + }; + Skill skill { + {ACTION}, + {ENTITY}, + {uri} + }; std::vector skills; skills.emplace_back(skill); innerBundleInfo.SetMainAbility(keyName); @@ -257,26 +294,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( @@ -288,7 +324,7 @@ FormInfo BmsBundleKitServiceTest::MockFormInfo( formInfo.abilityName = abilityName; formInfo.moduleName = moduleName; formInfo.package = PACKAGE_NAME; - formInfo.descriptionId = 123; + formInfo.descriptionId = FORMINFO_DESCRIPTIONID; formInfo.formConfigAbility = FORM_PATH; formInfo.description = FORM_DESCRIPTION; formInfo.defaultFlag = false; @@ -311,7 +347,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; @@ -333,12 +370,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( @@ -359,7 +396,8 @@ AbilityInfo BmsBundleKitServiceTest::MockAbilityInfo( abilityInfo.type = ABILITY_TYPE; abilityInfo.orientation = ORIENTATION; abilityInfo.launchMode = LAUNCH_MODE; - abilityInfo.formEntity = {"homeScreen","searchbox"}, + abilityInfo.configChanges = {"locale"}; + abilityInfo.formEntity = 1; abilityInfo.defaultFormHeight = DEFAULT_FORM_HEIGHT; abilityInfo.defaultFormWidth = DEFAULT_FORM_WIDTH; abilityInfo.codePath = CODE_PATH; @@ -367,15 +405,51 @@ 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"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; abilityInfo.metaData = metaData; 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 { @@ -446,25 +520,55 @@ 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( + const std::string &bundleName, const std::string &abilityName, const CompatibleAbilityInfo &abilityInfo) const +{ + EXPECT_EQ(abilityName, abilityInfo.name); + EXPECT_EQ(bundleName, abilityInfo.bundleName); + EXPECT_EQ(LABEL, abilityInfo.label); + EXPECT_EQ(DESCRIPTION, abilityInfo.description); + EXPECT_EQ(DEVICE_ID, abilityInfo.deviceId); + EXPECT_EQ(ICON_PATH, abilityInfo.iconPath); + 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(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 +{ + EXPECT_EQ(bundleName, appInfo.name); + EXPECT_EQ(BUNDLE_LABEL, appInfo.label); + EXPECT_EQ(BUNDLE_DESCRIPTION, appInfo.description); + EXPECT_EQ(PROCESS_TEST, appInfo.process); + EXPECT_EQ(permissionSize, static_cast(appInfo.permissions.size())); } void BmsBundleKitServiceTest::CheckModuleInfo(const HapModuleInfo &hapModuleInfo) const @@ -547,12 +651,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"; } } @@ -567,25 +671,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 @@ -600,7 +704,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, 123); + EXPECT_EQ(formInfo.descriptionId, FORMINFO_DESCRIPTIONID); EXPECT_EQ(formInfo.deepLink, FORM_PATH); EXPECT_EQ(formInfo.package, PACKAGE_NAME); EXPECT_EQ(formInfo.formVisibleNotify, true); @@ -630,7 +734,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, 123); + EXPECT_EQ(formInfo.descriptionId, FORMINFO_DESCRIPTIONID); EXPECT_EQ(formInfo.deepLink, FORM_PATH); EXPECT_EQ(formInfo.package, PACKAGE_NAME); EXPECT_EQ(formInfo.formVisibleNotify, true); @@ -648,7 +752,7 @@ void BmsBundleKitServiceTest::CheckFormInfoDemo(const std::vector &for } } -void BmsBundleKitServiceTest::CheckShortcutInfoTest(std::vector &shortcutInfos) const +void BmsBundleKitServiceTest::CheckShortcutInfoTest(std::vector &shortcutInfos) const { for (const auto &shortcutInfo : shortcutInfos) { EXPECT_EQ(shortcutInfo.id, SHORTCUT_TEST_ID); @@ -667,7 +771,7 @@ void BmsBundleKitServiceTest::CheckShortcutInfoTest(std::vector &s } } -void BmsBundleKitServiceTest::CheckShortcutInfoDemo(std::vector &shortcutInfos) const +void BmsBundleKitServiceTest::CheckShortcutInfoDemo(std::vector &shortcutInfos) const { for (const auto &shortcutInfo : shortcutInfos) { EXPECT_EQ(shortcutInfo.id, SHORTCUT_DEMO_ID); @@ -756,7 +860,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); } @@ -797,7 +901,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); @@ -817,7 +921,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); @@ -834,7 +938,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); } /** @@ -850,13 +954,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); @@ -876,7 +980,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); @@ -895,7 +999,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); @@ -912,8 +1016,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); } @@ -930,7 +1034,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); @@ -954,9 +1058,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); @@ -976,8 +1080,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); @@ -994,8 +1098,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); } /** @@ -1467,7 +1571,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); @@ -1487,7 +1591,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); @@ -1506,7 +1610,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); } @@ -2017,7 +2121,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(); @@ -2037,8 +2141,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(); @@ -2059,7 +2163,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(); @@ -2088,14 +2192,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(); @@ -2124,14 +2228,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(); @@ -2753,4 +2857,281 @@ HWTEST_F(BmsBundleKitServiceTest, GetShortcutInfos_0500, Function | SmallTest | std::vector shortcutInfos; GetBundleDataMgr()->GetShortcutInfos(BUNDLE_NAME_TEST, shortcutInfos); 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 + * @tc.desc: 1.can get compatibleAbilityInfo + */ +HWTEST_F(BmsBundleKitServiceTest, Ability_0100, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + Want want; + want.SetElementName(BUNDLE_NAME_TEST, ABILITY_NAME_TEST); + AbilityInfo abilityInfo; + bool testRet = GetBundleDataMgr()->QueryAbilityInfo(want, abilityInfo); + EXPECT_TRUE(testRet); + CompatibleAbilityInfo compatibleAbilityInfo; + abilityInfo.ConvertToCompatiableAbilityInfo(compatibleAbilityInfo); + CheckCompatibleAbilityInfo(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, compatibleAbilityInfo); + MockUninstallBundle(BUNDLE_NAME_TEST); +} + +/** + * @tc.number: Ability_0200 + * @tc.name: test can get the compatibleAbilityInfo by two bundle + * @tc.desc: 1.can get compatibleAbilityInfo + */ +HWTEST_F(BmsBundleKitServiceTest, Ability_0200, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + MockInstallBundle(BUNDLE_NAME_DEMO, MODULE_NAME_DEMO, ABILITY_NAME_DEMO); + Want want1; + want1.SetElementName(BUNDLE_NAME_TEST, ABILITY_NAME_TEST); + AbilityInfo abilityInfo1; + bool testRet1 = GetBundleDataMgr()->QueryAbilityInfo(want1, abilityInfo1); + EXPECT_TRUE(testRet1); + CompatibleAbilityInfo compatibleAbilityInfo1; + abilityInfo1.ConvertToCompatiableAbilityInfo(compatibleAbilityInfo1); + CheckCompatibleAbilityInfo(BUNDLE_NAME_TEST, ABILITY_NAME_TEST, compatibleAbilityInfo1); + Want want2; + want2.SetElementName(BUNDLE_NAME_DEMO, ABILITY_NAME_DEMO); + AbilityInfo abilityInfo2; + bool testRet2 = GetBundleDataMgr()->QueryAbilityInfo(want2, abilityInfo2); + EXPECT_TRUE(testRet2); + CompatibleAbilityInfo compatibleAbilityInfo2; + abilityInfo2.ConvertToCompatiableAbilityInfo(compatibleAbilityInfo2); + CheckCompatibleAbilityInfo(BUNDLE_NAME_DEMO, ABILITY_NAME_DEMO, compatibleAbilityInfo2); + MockUninstallBundle(BUNDLE_NAME_TEST); + MockUninstallBundle(BUNDLE_NAME_DEMO); +} + +/** + * @tc.number: Application_0100 + * @tc.name: test can get the compatibleApplicationInfo by one bundle + * @tc.desc: 1.can get compatibleApplicationInfo + */ +HWTEST_F(BmsBundleKitServiceTest, Application_0100, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + + ApplicationInfo testResult; + bool testRet = GetBundleDataMgr()->GetApplicationInfo( + BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, testResult); + EXPECT_TRUE(testRet); + CompatibleApplicationInfo appInfo; + testResult.ConvertToCompatibleApplicationInfo(appInfo); + CheckCompatibleApplicationInfo(BUNDLE_NAME_TEST, PERMISSION_SIZE_ZERO, appInfo); + + MockUninstallBundle(BUNDLE_NAME_TEST); +} + +/** + * @tc.number: Application_0100 + * @tc.name: test can get the compatibleApplicationInfo by two bundle + * @tc.desc: 1.can get compatibleApplicationInfo + */ +HWTEST_F(BmsBundleKitServiceTest, Application_0200, Function | SmallTest | Level1) +{ + MockInstallBundle(BUNDLE_NAME_TEST, MODULE_NAME_TEST, ABILITY_NAME_TEST); + MockInstallBundle(BUNDLE_NAME_DEMO, MODULE_NAME_DEMO, ABILITY_NAME_DEMO); + + ApplicationInfo testResult1; + bool testRet1 = GetBundleDataMgr()->GetApplicationInfo( + BUNDLE_NAME_TEST, ApplicationFlag::GET_BASIC_APPLICATION_INFO, DEFAULT_USER_ID_TEST, testResult1); + EXPECT_TRUE(testRet1); + CompatibleApplicationInfo appInfo1; + testResult1.ConvertToCompatibleApplicationInfo(appInfo1); + CheckCompatibleApplicationInfo(BUNDLE_NAME_TEST, PERMISSION_SIZE_ZERO, appInfo1); + + ApplicationInfo testResult2; + bool testRet2 = GetBundleDataMgr()->GetApplicationInfo( + 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..f00af36b414a1beda6690345006a9e9edab5d5de 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 @@ -82,8 +82,8 @@ const nlohmann::json CONFIG_JSON = R"( "icon": "$media:icon", "intents": [ { - "targetBundle": "com.huawei.hiworld.himusic", - "targetClass": "com.huawei.hiworld.himusic.entry.MainAbility" + "targetBundle": "com.demo.hiworld.himusic", + "targetClass": "com.demo.hiworld.himusic.entry.MainAbility" } ] } @@ -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..e0e103aabe28fb26df02a364ec7882d35831a810 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 @@ -165,13 +165,15 @@ const DefPermission DEFPERMISSION_MUSIC = { .description = DEF_LABEL1, .descriptionId = 1 }; -const DefPermission DEFPERMISSION_APP = {.name = DEFPERMISSION_NAME_APP, +const DefPermission DEFPERMISSION_APP = { + .name = DEFPERMISSION_NAME_APP, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; + .descriptionId = 1 +}; const DefPermission DEFPERMISSION_WECHAT = { .name = DEFPERMISSION_NAME_WECHAT, .grantMode = "system_grant", @@ -417,10 +419,26 @@ void BmsBundlePermissionTest::MockDefPermissionBundleSystemGrant(InnerBundleInfo moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -461,10 +479,26 @@ void BmsBundlePermissionTest::MockUpdateDefPermissionBundleSystemGrant(InnerBund moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -505,10 +539,26 @@ void BmsBundlePermissionTest::MockDefPermissionBundleTestReqpermission(InnerBund moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -548,10 +598,26 @@ void BmsBundlePermissionTest::MockNoDefPermissionBundle(InnerBundleInfo &innerbu moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -592,10 +658,26 @@ void BmsBundlePermissionTest::MockNoAvailableScopeDefPermissionBundle(InnerBundl moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -641,10 +723,26 @@ void BmsBundlePermissionTest::MockDefPermissionBundleUserGrant(InnerBundleInfo & moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -686,10 +784,26 @@ void BmsBundlePermissionTest::MockSameDefPermissionNameBundleSystemGrant(InnerBu moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -730,10 +844,26 @@ void BmsBundlePermissionTest::MockDefPermissionBundleSame(InnerBundleInfo &inner moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -775,10 +905,26 @@ void BmsBundlePermissionTest::MockReqPermissionBundle(InnerBundleInfo &innerbund moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -819,10 +965,26 @@ void BmsBundlePermissionTest::MockOtherReqPermissionBundle(InnerBundleInfo &inne moduleInfo.moduleName = PACKAGE_NAME; moduleInfo.description = BUNDLE_DESCRIPTION; - AppExecFwk::Parameters parameters{"description", "name", "type"}; - AppExecFwk::Results results{"description", "name", "type"}; - AppExecFwk::CustomizeData customizeData{"name", "value", "extra"}; - MetaData metaData{{parameters}, {results}, {customizeData}}; + AppExecFwk::Parameters parameters { + "description", + "name", + "type" + }; + AppExecFwk::Results results { + "description", + "name", + "type" + }; + AppExecFwk::CustomizeData customizeData { + "name", + "value", + "extra" + }; + MetaData metaData { + {parameters}, + {results}, + {customizeData} + }; moduleInfo.metaData = metaData; innerbundleinfo.SetCurrentModulePackage(PACKAGE_NAME); innerbundleinfo.SetBaseApplicationInfo(appInfo); @@ -843,7 +1005,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 +1035,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 +1050,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 +1072,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 +1086,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 +1173,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 +1205,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 +1257,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 +1285,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 +1361,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 +1451,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 +1540,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 +1556,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 +1595,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 +1611,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 +1641,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 +1671,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 +1690,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 +1709,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 +1736,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 +1780,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 +1802,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 +1822,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 +1840,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..3ab3580bd54ff426745a4d9b945a53474f2f6e85 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 @@ -296,11 +296,11 @@ void BmsBundleUninstallerTest::ClearBundleInfoInDb() return; } auto dataMgt = bundleMgrService_->GetDataMgr(); - if(dataMgt == nullptr) { + if (dataMgt == nullptr) { return; } auto dataStorage = dataMgt->GetDataStorage(); - if(dataStorage == nullptr) { + if (dataStorage == nullptr) { return; } InnerBundleInfo innerBundleInfo; @@ -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..3ea0d14f357922e0d96d6f6eed5649b8ad0f4882 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); @@ -67,12 +67,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0100, Function | SmallTest | Level0) * @tc.desc: 1. the service is already initialized * 2. the initialized BMS service can be stopped */ -HWTEST_F(BmsServiceStartupTest, Startup_0200,Function | SmallTest | Level0) +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); @@ -84,15 +84,15 @@ HWTEST_F(BmsServiceStartupTest, Startup_0200,Function | SmallTest | Level0) * @tc.desc: 1. the service is already initialized * 2. the stopped BMS service can be restarted */ -HWTEST_F(BmsServiceStartupTest, Startup_0300,Function | SmallTest | Level0) +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); @@ -104,12 +104,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0300,Function | SmallTest | Level0) * @tc.desc: 1. the service is already initialized * 2. the recall start function will not affect the initialized BMS service */ -HWTEST_F(BmsServiceStartupTest, Startup_0400,Function | SmallTest | Level0) +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); @@ -121,7 +121,7 @@ HWTEST_F(BmsServiceStartupTest, Startup_0400,Function | SmallTest | Level0) * @tc.desc: 1. the service is already initialized * 2. the dataMgr can be obtained */ -HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100,Function | SmallTest | Level0) +HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -136,7 +136,7 @@ HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100,Function | SmallTest | Level0) * @tc.desc: 1. the service is already initialized * 2. the installer can be obtained */ -HWTEST_F(BmsServiceStartupTest, GetBundleInstaller_0100,Function | SmallTest | Level0) +HWTEST_F(BmsServiceStartupTest, GetBundleInstaller_0100, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); diff --git a/services/formmgr/BUILD.gn b/services/formmgr/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1ea0f1282196c4a211a6ac9684ecf7344db72ddb --- /dev/null +++ b/services/formmgr/BUILD.gn @@ -0,0 +1,117 @@ +# 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", + + # "//base/miscservices/time/interfaces/innerkits/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", + "${libs_path}/libeventhandler:libeventhandler_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//utils/native/base:utils", + + # "//third_party/libuuid:libuuid_static", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "ces_standard:cesfwk_core", + "ces_standard:cesfwk_innerkits", + "dmsfwk_standard:zuri", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "os_account_standard:libaccountkits", + "os_account_standard:libaccountkits", + "permission_standard:libpermissionsdk_standard", + "power_manager_native:powermgr_client", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + 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..0cf36c49c5d58b2888dcdffe1173cbcefc74fd0a --- /dev/null +++ b/services/formmgr/include/form_ability_connection.h @@ -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. + */ + +#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); + /** + * @brief Get the provider Key + * + * @return The provider Key + */ + std::string GetProviderKey(); + /** + * @brief Set the Provider Key + * + * @param bundleName bundleName + * @param abilityName abilityName + */ + void SetProviderKey(const std::string &bundleName, const std::string &abilityName); + +private: + int64_t formId_ = 0; + std::string deviceId_ = ""; + std::string bundleName_ = ""; + std::string abilityName_ = ""; + bool isFreeInstall_ = false; + 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..effd42988ebcc115da1cadd16b48fc37a0bd55a8 --- /dev/null +++ b/services/formmgr/include/form_ams_helper.h @@ -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. + */ + +#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 "event_handler.h" +#include "iremote_object.h" +#include "uri.h" + +namespace OHOS { +namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; +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 SetEventHandler. + * @param handler event handler + */ + inline void SetEventHandler(const std::shared_ptr &handler) + { + eventHandler_ = handler; + } + /** + * @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 Disconnect ability delay, 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 DisConnectServiceAbilityDelay(const sptr &connect); + /** + * @brief Add the ability manager instance for debug. + * @param abilityManager the ability manager ipc object. + */ + void SetAbilityManager(const sptr &abilityManager); +private: + /** + * @brief Disconnect ability task, 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. + */ + void DisConnectAbilityTask(const sptr &connect); +private: + sptr abilityManager_ = nullptr; + std::shared_ptr eventHandler_ = 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..2f0ca0bafb4bd3450affd2ac37dc2692de7e623d --- /dev/null +++ b/services/formmgr/include/form_batch_delete_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_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, const std::string &bundleName, + const std::string &abilityName); + 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..4e5523ba3bc681a495af091c8a76ca6f767a5ad7 --- /dev/null +++ b/services/formmgr/include/form_bms_helper.h @@ -0,0 +1,79 @@ +/* + * 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 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..6a930ceca8a75c31d3f4d27e5134804c114af1eb --- /dev/null +++ b/services/formmgr/include/form_cast_temp_connection.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 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, const std::string &bundleName, + const std::string &abilityName); + 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..b8114dc3aef1b031452e52c456c7caf66760a8a2 --- /dev/null +++ b/services/formmgr/include/form_data_mgr.h @@ -0,0 +1,402 @@ +/* + * 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 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); + + /** + * @brief Update form for host clients. + * @param formId The Id of the form. + * @param formProviderInfo FormProviderInfo object + */ + void UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo); +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..329b56d677377cb2d57893b95d779c1e4c934e2a --- /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, const std::string &bundleName, const std::string &abilityName); + 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..88a51f43da110e7047d7bd34bd68314edbd737bb --- /dev/null +++ b/services/formmgr/include/form_event_notify_connection.h @@ -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. + */ + +#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, + const std::string &bundleName, const std::string &abilityName); + 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..4d4b5ee895858af2cfedb97328f436ad1367429f --- /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_ = 0; + 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..3106ed83c82e0e4c08ceac03e5cf6540028e7615 --- /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_ = 0; + bool updateFlag_ = false; + int32_t updateDuration_ = 0; + std::string scheduledUpdateTime_ = ""; + std::vector hapSourceDirs_; + bool temporaryFlag_ = false; + bool formVisibleNotify_ = false; + + 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..2ac902fc6f4ee5a37c9eebdc719c11fa5f649f9f --- /dev/null +++ b/services/formmgr/include/form_mgr_adapter.h @@ -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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H + +#include +#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 final : public DelayedRefSingleton { +DECLARE_DELAYED_REF_SINGLETON(FormMgrAdapter) +public: + DISALLOW_COPY_AND_MOVE(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); + + /** + * @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); +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..ac10b21ae6a2a392f596c3e16d6dca6550335edc --- /dev/null +++ b/services/formmgr/include/form_mgr_service.h @@ -0,0 +1,210 @@ +/* + * 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_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; + + 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..1aefe943954c21e19249aa3af8e601d00665f363 --- /dev/null +++ b/services/formmgr/include/form_msg_event_connection.h @@ -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. + */ + +#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, + const std::string &bundleName, const std::string &abilityName); + 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..a847be922893c1ba524949925668f9a7ebfdc6d4 --- /dev/null +++ b/services/formmgr/include/form_refresh_connection.h @@ -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. + */ + +#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, + const std::string &bundleName, const std::string &abilityName); + 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..38487b5fa1b967e23cae2f1adb405c636292695c --- /dev/null +++ b/services/formmgr/include/form_supply_callback.h @@ -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. + */ + +#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: + /** + * @brief check if disconnect ability or not. + * @param connection The ability connection. + */ + bool CanDisConnect(sptr &connection); +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..cec511f4f4a7be46636ffd088eea2b8620ab268f --- /dev/null +++ b/services/formmgr/include/form_timer.h @@ -0,0 +1,148 @@ +/* + * 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 = UpdateType::TYPE_INTERVAL_CHANGE; + + FormTimer() + { + formId = -1; + period = -1; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = false; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + + FormTimer(int64_t id, bool countTimer) + { + formId = id; + period = -1; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = countTimer; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + + FormTimer(int64_t id, long repeatTime) + { + formId = id; + period = repeatTime; + hour = -1; + min = -1; + isUpdateAt = false; + isCountTimer = true; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + + FormTimer(int64_t id, int hourTime, int minTime) + { + formId = id; + hour = hourTime; + min = minTime; + period = -1; + isUpdateAt = true; + isCountTimer = false; + refreshTime = 0; + type = UpdateType::TYPE_INTERVAL_CHANGE; + } + ~FormTimer(void){ + } +}; +/** + * @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; + } + ~DynamicRefreshItem(void){ + } +}; +/** + * @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; +}; + +} // 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..1ff69380079bdb562a21b9d0e7305aad3ef7901c --- /dev/null +++ b/services/formmgr/include/form_timer_mgr.h @@ -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. + */ + +#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. + * @return Returns true on success, false on failure. + */ + bool HandleSystemTimeChanged(); + /** + * @brief Reset form limiter. + * @return Returns true on success, false on failure. + */ + bool HandleResetLimiter(); + /** + * @brief Update attime trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ + bool OnUpdateAtTrigger(long updateTime); + /** + * @brief Dynamic time trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ + bool 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. + * @return Returns true on success, false on failure. + */ + bool 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 Clear limiter timer resource. + */ + void ClearLimiterTimerResource(); + /** + * @brief Delete dynamic refresh item. + * @param formId The Id of the form. + * @return Returns true on success, false on failure. + */ + bool 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_ = nullptr; + OHOS::ThreadPool* taskExecutor_ = nullptr; + + uint64_t intervalTimerId_ = 0L; + uint64_t updateAtTimerId_ = 0L; + uint64_t dynamicAlarmTimerId_ = 0L; + uint64_t limiterTimerId_= 0L; + + + +}; + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_MGR_H diff --git a/services/formmgr/include/form_timer_option.h b/services/formmgr/include/form_timer_option.h new file mode 100644 index 0000000000000000000000000000000000000000..d026163ee46779b03b3e08f36f4e6b75e34d86aa --- /dev/null +++ b/services/formmgr/include/form_timer_option.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_TIMER_INFO_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H + +#include "itimer_info.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormTimerOption + * form timer option. + */ +class FormTimerOption : public OHOS::MiscServices::ITimerInfo { +public: + FormTimerOption(); + virtual ~FormTimerOption(); + 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; +}; + +FormTimerOption::FormTimerOption() +{ +} + +FormTimerOption::~FormTimerOption() +{ +} + +void FormTimerOption::OnTrigger() +{ + callBack(); +} + +void FormTimerOption::SetCallbackInfo(std::function callBack) +{ + this->callBack = callBack; +} + +void FormTimerOption::SetType(const int &type) +{ + this->type = type; +} + +void FormTimerOption::SetRepeat(bool repeat) +{ + this->repeat = repeat; +} +void FormTimerOption::SetInterval(const uint64_t &interval) +{ + this->interval = interval; +} +void FormTimerOption::SetWantAgent(std::shared_ptr _wantAgent) +{ + this->wantAgent = _wantAgent; +} + +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H diff --git a/services/formmgr/include/form_util.h b/services/formmgr/include/form_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d31b79dda6d239a0cb485b977bd6cb3e7df1570e --- /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(uint64_t formId, uint64_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..35c58ca9ea98c75892555179ba81b52e76c49b22 --- /dev/null +++ b/services/formmgr/src/form_ability_connection.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 + +#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, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, formId_, resultCode); + return; + } + + 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_; +} +/** + * @brief Get the provider Key + * + * @return The provider Key + */ +std::string FormAbilityConnection::GetProviderKey() +{ + if(bundleName_.empty() || abilityName_.empty()) { + return ""; + } + return bundleName_ + "::" + abilityName_; +} + +/** + * @brief Set the Provider Key + * + * @param bundleName bundleName + * @param abilityName abilityName + */ +void FormAbilityConnection::SetProviderKey(const std::string &bundleName, const std::string &abilityName) +{ + bundleName_ = bundleName; + abilityName_ = 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..3cd1770f269ea7642e4e52e5850075f489534c8b --- /dev/null +++ b/services/formmgr/src/form_acquire_connection.cpp @@ -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. + */ + +#include + +#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) +{ + SetProviderKey(info.GetProviderBundleName(), info.GetAbilityName()); +} +/** + * @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}" PRId64 ", 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..7588442f149637b44f0a691b6096a44980cc19b6 --- /dev/null +++ b/services/formmgr/src/form_ams_helper.cpp @@ -0,0 +1,134 @@ +/* + * 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 { +const int FORM_DISCONNECT_DELAY_TIME = 100; // ms +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 Disconnect ability, 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) +{ 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->DisconnectAbility(connect); +} +/** + * @brief Disconnect ability delay, 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::DisConnectServiceAbilityDelay(const sptr &connect) +{ + if (eventHandler_ == nullptr) { + APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); + return ERR_INVALID_OPERATION; + } + std::function disConnectAbilityFunc = std::bind( + &FormAmsHelper::DisConnectAbilityTask, + this, + connect); + if(!eventHandler_->PostTask(disConnectAbilityFunc, FORM_DISCONNECT_DELAY_TIME)) { + APP_LOGE("%{public}s, failed to disconnect ability", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} +/** + * @brief Add the ability manager instance for debug. + * @param abilityManager the ability manager ipc object. + */ +void FormAmsHelper::SetAbilityManager(const sptr &abilityManager) +{ + abilityManager_ = abilityManager; +} + +/** + * @brief Disconnect ability task, 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. + */ +void FormAmsHelper::DisConnectAbilityTask(const sptr &connect) +{ + sptr ams = GetAbilityManager(); + if (ams == nullptr) { + APP_LOGE("%{public}s, ability service not connect", __func__); + return; + } + ams->DisconnectAbility(connect); +} +} // 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..72935c04c17edbea20160a1abf9646940be2b71f --- /dev/null +++ b/services/formmgr/src/form_batch_delete_connection.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 "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, + const std::string &bundleName, const std::string &abilityName) + :formIds_(formIds) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @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..2f2a0d8e53a6e02350a4610dc2f9aad7d0e2a100 --- /dev/null +++ b/services/formmgr/src/form_bms_helper.cpp @@ -0,0 +1,110 @@ +/* + * 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(); + + 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..e39ae1f08fe26152904d78e798e9d4d0e4e84a04 --- /dev/null +++ b/services/formmgr/src/form_cast_temp_connection.cpp @@ -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. + */ + +#include + +#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, const std::string &bundleName, + const std::string &abilityName) + :formId_(formId) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @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}" PRId64 ", 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..d845fc5760b438fdd940c45c35e2b3be7e12b892 --- /dev/null +++ b/services/formmgr/src/form_data_mgr.cpp @@ -0,0 +1,1140 @@ +/* + * 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_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 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; +} +/** + * @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); + return ERR_APPEXECFWK_FORM_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_APPEXECFWK_FORM_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_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT; + } + } + } + } + } + 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 false; + } + 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() +{ + // generate udidHash_ + if (udidHash_ < 0) { + APP_LOGE("%{public}s fail, generateFormId no invalid udidHash_", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + 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 formProviderInfo FormProviderInfo object + */ +void FormDataMgr::UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo) +{ + 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.formProviderInfo = formProviderInfo; +} +/** + * @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}" PRId64 " is less than 0", __func__, formId); + continue; + } + + int64_t matchedFormId = FindMatchedFormId(formId); + if (!itHostRecord->Contains(matchedFormId)) { + APP_LOGW("%{public}s, form %{public}" PRId64 " 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}" PRId64 "", __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_APPEXECFWK_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) +{ + uint64_t unsignedFormId = static_cast(formId); + if ((unsignedFormId & 0xffffffff00000000L) != 0) { + return formId; + } + std::lock_guard lock(formRecordMutex_); + std::map::iterator itFormRecord; + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + uint64_t unsignedFormId = static_cast(formId); + uint64_t unsignedItFormRecordFirst = static_cast(itFormRecord->first); + if ((unsignedItFormRecordFirst & 0x00000000ffffffffL) == (unsignedFormId & 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; + formIdKey.moduleName = ""; + formIdKey.formName = ""; + formIdKey.specificationId = 0; + formIdKey.orientation = 0; + 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..1625e676ecb3846927d9455dcf13606a3ee893f5 --- /dev/null +++ b/services/formmgr/src/form_db_cache.cpp @@ -0,0 +1,281 @@ +/* + * 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); + } +} + +/** + * @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}" PRId64 "", __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}" PRId64 "].", __func__, formDBInfo.formId); + *iter = formDBInfo; + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->ModifyStorageFormInfo(innerFormInfo); + } else { + APP_LOGW("%{public}s, already exist, formId[%{public}" PRId64 "].", __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}" PRId64 "", __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}" PRId64 "].", __func__, formDBInfo.formId); + *iter = formDBInfo; + InnerFormInfo innerFormInfo(formDBInfo); + return dataStorage_->ModifyStorageFormInfo(innerFormInfo); + } else { + APP_LOGW("%{public}s, already exist, formId[%{public}" PRId64 "].", __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}" PRId64 "]", __func__, formId); + } else { + formDBInfos_.erase(iter); + } + if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { + return ERR_OK; + } else { + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } +} +/** + * @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; +} + +/** + * @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}" PRId64 "]", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; +} +/** + * @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}" PRId64 "]", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; +} +/** + * @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); +} +/** + * @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; + formIdKey.moduleName = ""; + formIdKey.formName = ""; + formIdKey.specificationId = 0; + formIdKey.orientation = 0; + 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..f47f45c4f75f789c13fe28dee49f1ad376f98ba4 --- /dev/null +++ b/services/formmgr/src/form_db_info.cpp @@ -0,0 +1,79 @@ +/* + * 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"; +} + +/** + * @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; +} + +/** + * @brief Transform the json object to InnerFormInfo object. + * @param jsonObject Indicates the obtained json object. + * @return + */ +bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) +{ + 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>(); + + return true; +} + +void InnerFormInfo::AddUserUid(const int callingUid) +{ + 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) +{ + 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..77e3ea378936cb8c57ec61c6259a9f698c48427c --- /dev/null +++ b/services/formmgr/src/form_delete_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 + +#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, const std::string &bundleName, + const std::string &abilityName) + :formId_(formId) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @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}" PRId64 ", 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..1961cc2ff567e81ad602ff5d431a8607d19c1320 --- /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..6933e3887e49ab5066893b3adc6719ad917ca930 --- /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, const std::string &bundleName, const std::string &abilityName) + :formEvents_(formEvents), + formVisibleType_(formVisibleType) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @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..6348112c8112b8d0a394314fd785b88985619862 --- /dev/null +++ b/services/formmgr/src/form_host_callback.cpp @@ -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. + */ + +#include + +#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}" PRId64 "", 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}" PRId64 ".", __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..2644d0273c280c46033eaaccd1db0547d996dbe2 --- /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..fbb58c77909314b6c952a733bce87ce9c54240a8 --- /dev/null +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -0,0 +1,1451 @@ +/* + * 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_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_interface.h" +#include "form_provider_mgr.h" +#include "form_supply_callback.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 { +FormMgrAdapter::FormMgrAdapter() +{ +}; +FormMgrAdapter::~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 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}" PRId64 "", __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_APPEXECFWK_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_APPEXECFWK_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_APPEXECFWK_FORM_COMMON_CODE; + } + 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}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_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}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + APP_LOGD("%{public}s, release formRecords, formId: %{public}" PRId64 "", __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_APPEXECFWK_FORM_COMMON_CODE; + } + } + 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}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_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}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_OPERATION_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}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_OPERATION_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}zu", __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}" PRId64 "", __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_APPEXECFWK_FORM_COMMON_CODE; + } + return ERR_OK; + } + + if (result = FormDbCache::GetInstance().UpdateDBRecord(formId, dbRecord); result != ERR_OK) { + return result; + } + + APP_LOGD("%{public}s, dbRecord.formUserUids size: %{public}zu", __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_APPEXECFWK_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_BMS_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_APPEXECFWK_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}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_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}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_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_APPEXECFWK_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 (formId <= 0 || 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}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_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_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (!formHostRecord.Contains(matchedFormId)) { + APP_LOGE("%{public}s fail, form is not self-owned.", __func__); + return ERR_APPEXECFWK_FORM_OPERATION_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_BMS_FAILED; + } + + int64_t matchedFormId; + std::map> eventMaps; + for (int64_t formId : formIds) { + if (formId <= 0) { + APP_LOGW("%{public}s, formId %{public}" PRId64 " 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}" PRId64 ".", __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}" PRId64 ".", __func__, matchedFormId); + continue; + } + + formRecord.formVisibleNotifyState = formVisibleType; + if (!FormDataMgr::GetInstance().UpdateFormRecord(matchedFormId, formRecord)) { + APP_LOGW("%{public}s fail, set formVisibleNotifyState error, formId:%{public}" PRId64 ".", + __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}" PRId64 ".", + __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}" PRId64 ".", + __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_APPEXECFWK_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}" PRId64 "", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_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}" PRId64 "", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + } + + int callingUid = IPCSkeleton::GetCallingUid(); + int checkCode = FormDataMgr::GetInstance().CheckEnoughForm(callingUid); + if (checkCode != 0) { + APP_LOGE("%{public}s, %{public}" PRId64 " 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}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_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}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + if (!FormDataMgr::GetInstance().ModifyFormTempFlg(matchedFormId, false)) { + APP_LOGE("%{public}s fail, modify form temp flag error, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + if (!FormDataMgr::GetInstance().AddFormUserUid(matchedFormId, callingUid)) { + APP_LOGE("%{public}s fail, add form user uid error, formId:%{public}" PRId64 ".", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + 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}" PRId64 ".", __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, + record.bundleName, record.abilityName); + + Want want; + want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + want.SetElementName(record.bundleName, record.abilityName); + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} +/** + * @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_NOT_EXIST_ID; + } +} +/** + * @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_NOT_EXIST_ID; + } +} +/** + * @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_NOT_EXIST_ID; + + 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}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_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}" PRId64 "", __func__, formId); + + // delete form data in provider + FormRecord delRecord; + delRecord.bundleName = info.GetProviderBundleName(); + delRecord.abilityName = info.GetAbilityName(); + FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, delRecord); + + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; +} +int64_t FormMgrAdapter::PaddingUDIDHash(const int64_t formId) const +{ + // Compatible with int form id. + uint64_t unsignedFormId = static_cast(formId); + if ((unsignedFormId & 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}" PRId64 "", __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}" PRId64 "", 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__); + size_t position = providerKey.find(Constants::NAME_DELIMITER); + std::string bundleName = providerKey.substr(0, position); + std::string abilityName = providerKey.substr(position + Constants::NAME_DELIMITER.size()); + sptr formEventNotifyConnection = new FormEventNotifyConnection(formIdsByProvider, + formVisibleType, bundleName, abilityName); + Want connectWant; + connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); + + connectWant.SetElementName(bundleName, abilityName); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formEventNotifyConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + + 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); + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} + +/** + * @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_BMS_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.bundleName == bundleName && abilityInfo.moduleName == moduleName ) { + packageName = bundleName + moduleName; + 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_BMS_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; + formInfo.moduleName = moduleName; + APP_LOGD("GetFormInfo end."); + return ERR_OK; + } + } + } else { + for (const auto &form : formInfos) { + if (form.name == formName) { + formInfo = form; + formInfo.moduleName = moduleName; + 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; + } + + if (ErrCode ret = CreateFormItemInfo(bundleInfo, formInfo, formItemInfo); ret != ERR_OK) { + return ret; + } + 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_BMS_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.moduleName); // 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); + } + } + + APP_LOGI("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size()); + for (const auto &item : bundleInfo.applicationInfo.moduleInfos) { + APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, + item.moduleName.c_str(), item.moduleSourceDir.c_str()); + 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}" PRId64 ",nextTime:%{public}" PRId64 "", __func__, formId, nextTime); + if (formId <= 0) { + APP_LOGE("%{public}s form formId or bundleName is invalid", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); + + std::string bundleName; + if (!GetBundleName(bundleName)) { + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + } + + FormRecord formRecord; + if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { + APP_LOGE("%{public}s, not found in formrecord.", __func__); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + // check bundleName + if (bundleName != formRecord.bundleName) { + APP_LOGE("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str()); + return ERR_APPEXECFWK_FORM_OPERATION_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_APPEXECFWK_FORM_MAX_REFRESH; + } + + if (!FormTimerMgr::GetInstance().SetNextRefreshTime(formId, nextTime)) { + APP_LOGE("%{public}s failed", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + 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}" PRId64 "", __func__, matchedFormId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + 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_COMMON_CODE; + } + + if (!formHostRecord.Contains(matchedFormId)) { + APP_LOGE("%{public}s failed, form is not self-owned.", __func__); + return ERR_APPEXECFWK_FORM_OPERATION_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_APPEXECFWK_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}" PRId64 "", __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 true on success, false on failure. + */ +bool FormMgrAdapter::IsFormCached(const FormRecord record) +{ + if (record.versionUpgrade) { + return false; + } + return true; +} + +/** + * @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 FormMgrAdapter::AcquireProviderFormInfo(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->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 FormMgrAdapter::NotifyFormDelete(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->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__); + } +} +} // 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..8f25249579aa31e8c31de74365c615b143db74da --- /dev/null +++ b/services/formmgr/src/form_mgr_service.cpp @@ -0,0 +1,371 @@ +/* + * 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_ams_helper.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_mgr_adapter.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) +{ +} + +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::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().EnableUpdateForm(formIds, callerToken); + } else { + return FormMgrAdapter::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().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::GetInstance().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_); + FormAmsHelper::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() +{ + return true; +} + +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..570e77e9794c5ffdb3ca19a3e18f5c1816ecde58 --- /dev/null +++ b/services/formmgr/src/form_msg_event_connection.cpp @@ -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. + */ + +#include + +#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, + const std::string &bundleName, const std::string &abilityName) + :formId_(formId), + want_(want) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @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}" PRId64 ", 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..3712752d68c9a9de0f26899d66461897b5eea5a2 --- /dev/null +++ b/services/formmgr/src/form_provider_mgr.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 + +#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}" PRId64 "", __func__, formId); + + if (formId <= 0) { + APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); + return ERR_APPEXECFWK_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}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + FormHostRecord clientHost; + bool isGetFormHostRecord = FormDataMgr::GetInstance().GetFormHostRecord(formId, clientHost); + if (!isGetFormHostRecord) { + APP_LOGE("%{public}s fail, clientHost is null", __func__); + return ERR_APPEXECFWK_FORM_COMMON_CODE; + } + + 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}" PRId64 ".", __func__, formId); + FormRecord record; + bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record); + if (!bGetRecord) { + APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, formId); + return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + } + + 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, + record.bundleName, record.abilityName); + 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_PROVIDER_DEL_FAIL; + } + } + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formRefreshConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + + 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_APPEXECFWK_FORM_INVALID_PARAM; + } + + if (formRecord.bundleName.empty()) { + APP_LOGE("%{public}s, formRecord.bundleName is empty.", __func__); + return ERR_APPEXECFWK_FORM_INVALID_PARAM; + } + + 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, + formRecord.bundleName, formRecord.abilityName); + Want want; + want.SetElementName(formRecord.bundleName, formRecord.abilityName); + want.SetFlags(Want::FLAG_ABILITY_FORM_ENABLED); + + ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection); + if (errorCode != ERR_OK) { + APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); + return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + return ERR_OK; +} + +/** + * @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, bundleName, abilityName); + 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 ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + 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}" PRId64 ".", __func__, formId); + return ERR_APPEXECFWK_FORM_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); + formRecord.formProviderInfo.SetUpgradeFlg(true); + } 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); + formRecord.formProviderInfo.SetUpgradeFlg(false); + } + } + // update formProviderInfo to formRecord + FormDataMgr::GetInstance().UpdateFormProviderInfo(formId, formRecord.formProviderInfo); + // 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}" PRId64 ".", __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, + record.bundleName, record.abilityName); + 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 ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + } + + 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}" PRId64 ".", __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..7fd2ecf6141335a17711001b4b5bbb1cb2101712 --- /dev/null +++ b/services/formmgr/src/form_refresh_connection.cpp @@ -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. + */ + +#include + +#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, + const std::string &bundleName, const std::string &abilityName) + :formId_(formId), + want_(want) +{ + SetProviderKey(bundleName, abilityName); +} +/** + * @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}" PRId64 ", 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); + } 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..b0c814350119063a76fae588206a1c44fc4b5cff --- /dev/null +++ b/services/formmgr/src/form_refresh_limiter.cpp @@ -0,0 +1,197 @@ +/* + * 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 "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}" PRId64 "", 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}" PRId64 ", 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}" PRId64 "", 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..7c3745ba00bc310b1f6a8cfbbae27615b797be1e --- /dev/null +++ b/services/formmgr/src/form_storage_mgr.cpp @@ -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. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "securec.h" +#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; +} + +/** + * @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_COMMON_CODE; + } + + 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_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%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_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%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_COMMON_CODE; + } + 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_COMMON_CODE; + } else { + ret = ERR_OK; + } + } else { + APP_LOGE("%{public}s, not find formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + } else { + APP_LOGE("%{public}s, file is empty formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_COMMON_CODE; + } + 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}" PRId64 "]", __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_COMMON_CODE; + } + } else { + closedir(dirptr); + } + char tmpFilePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf_s(tmpFilePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%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_COMMON_CODE; + } + 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_COMMON_CODE; + } + 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}" PRId64 "]", __func__, innerFormInfo.GetFormId()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%" PRId64 ".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_COMMON_CODE; + } + + 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_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%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_COMMON_CODE; + } + + 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..3fef6de0c6574e725202e0f71cd41817f45d641e --- /dev/null +++ b/services/formmgr/src/form_supply_callback.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 "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) +{ + APP_LOGI("%{public}s called.", __func__); + 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; + } + + std::string strFormId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); + int64_t formId = std::stoll(strFormId); + int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); + APP_LOGD("%{public}s come: %{public}" PRId64 ", %{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); + } + APP_LOGI("%{public}s end.", __func__); + 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) +{ + APP_LOGI("%{public}s called.", __func__); + 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); + APP_LOGI("%{public}s end.", __func__); + return ERR_OK; +} +/** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ +void FormSupplyCallback::AddConnection(sptr connection) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock_l(conMutex_); + long connectKey = FormUtil::GetCurrentMillisecond(); + while (connections_.find(connectKey) != connections_.end()) { + connectKey++; + } + connection->SetConnectId(connectKey); + connections_.emplace(connectKey, connection); + APP_LOGI("%{public}s end.", __func__); +} + +/** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ +void FormSupplyCallback::RemoveConnection(long connectId) +{ + APP_LOGI("%{public}s called.", __func__); + std::lock_guard lock_l(conMutex_); + auto conIterator = connections_.find(connectId); + if (conIterator != connections_.end()) { + sptr connection = conIterator->second; + if (connection != nullptr) { + if(CanDisConnect(connection)) { + FormAmsHelper::GetInstance().DisConnectServiceAbility(connection); + APP_LOGI("%{public}s end, disconnect service ability", __func__); + } else { + FormAmsHelper::GetInstance().DisConnectServiceAbilityDelay(connection); + APP_LOGI("%{public}s end, disconnect service ability delay", __func__); + } + } + connections_.erase(connectId); + } + APP_LOGI("%{public}s end.", __func__); +} +/** + * @brief check if disconnect ability or not. + * @param connection The ability connection. + */ +bool FormSupplyCallback::CanDisConnect(sptr &connection) +{ + APP_LOGI("%{public}s called.", __func__); + int count = 0; + for(auto &conn : connections_) { + if(connection->GetProviderKey() == conn.second->GetProviderKey()) { + APP_LOGI("%{public}s, key: %{public}s", __func__, conn.second->GetProviderKey().c_str()); + count++; + if(count > 1) { + APP_LOGI("%{public}s end, true.", __func__); + return true; + } + } + } + APP_LOGI("%{public}s end, false.", __func__); + return false; +} +} // 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..0fd6edcd7af5f3a947fd82dc5911b18e221b5c57 --- /dev/null +++ b/services/formmgr/src/form_sys_event_receiver.cpp @@ -0,0 +1,494 @@ +/* + * 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 "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}zu", __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}zu", __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}" PRId64 "", __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}" PRId64 "", __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}" PRId64 "", __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..cbaa7fa32fd2b5308990b800b20333bde68f2361 --- /dev/null +++ b/services/formmgr/src/form_task_mgr.cpp @@ -0,0 +1,508 @@ +/* + * 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 "form_constants.h" +#include "form_data_mgr.h" +#include "form_host_interface.h" +#include "form_item_info.h" +#include "form_mgr_adapter.h" +#include "form_provider_interface.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" + +namespace OHOS { +namespace AppExecFwk { +const int FORM_TASK_DELAY_TIME = 6; // ms +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, FORM_TASK_DELAY_TIME); +} +/** + * @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, FORM_TASK_DELAY_TIME); +} + +/** + * @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, FORM_TASK_DELAY_TIME); +} + +/** + * @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, FORM_TASK_DELAY_TIME); +} + +/** + * @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, FORM_TASK_DELAY_TIME); +} + +/** + * @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, FORM_TASK_DELAY_TIME); +} + +/** + * @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, FORM_TASK_DELAY_TIME); +} + +/** + * @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, FORM_TASK_DELAY_TIME); +} +/** + * @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, FORM_TASK_DELAY_TIME); +} +/** + * @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, FORM_TASK_DELAY_TIME); +} + +/** + * @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, FORM_TASK_DELAY_TIME); + 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) +{ + FormMgrAdapter::GetInstance().AcquireProviderFormInfo(formId, want, 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 FormTaskMgr::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) +{ + FormMgrAdapter::GetInstance().NotifyFormDelete(formId, want, 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 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}" PRId64 "", 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) +{ + APP_LOGI("%{public}s start", __func__); + 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(); + form.formProviderData = record.formProviderInfo.GetFormData(); + APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, + form.jsFormCodePath.c_str(), form.formData.c_str()); + 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..886cef74cc4f0a5dc65a47ca46c3e5052316a599 --- /dev/null +++ b/services/formmgr/src/form_timer_mgr.cpp @@ -0,0 +1,940 @@ +/* + * 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 "ability_context.h" +#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_option.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}" PRId64 "", __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}" PRId64 "", __func__, formId); + + if (!DeleteIntervalTimer(formId)) { + if (!DeleteUpdateAtTimer(formId)) { + APP_LOGE("%{public}s, failed to DeleteUpdateAtTimer", __func__); + return false; + } + } + + if (!DeleteDynamicItem(formId)) { + APP_LOGE("%{public}s, failed to DeleteDynamicItem", __func__); + return false; + } + 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); + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + 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; + } + } + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + + 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}" PRId64 ", 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}" PRId64 " 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 attimer 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}" PRId64 " task", __func__, task.formId); + return true; + } + intervalTimerTasks_.emplace(task.formId, task); + } + if(!UpdateLimiterAlarm()) { + APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); + return false; + } + 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. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::HandleSystemTimeChanged() +{ + APP_LOGI("%{public}s start", __func__); + if (!updateAtTimerTasks_.empty()) { + return UpdateAtTimerAlarm(); + } + + APP_LOGI("%{public}s end", __func__); + return true; +} +/** + * @brief Reset form limiter. + * @return Returns true on success, false on failure. + */ +bool 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__); + return true; +} +/** + * @brief Update attime trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ +bool 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); + } + } + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + + 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__); + return true; +} +/** + * @brief Dynamic time trigger. + * @param updateTime Update time. + * @return Returns true on success, false on failure. + */ +bool 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); + } + + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to update dynamic alarm.", __func__); + return false; + } + + 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__); + return true; +} +/** + * @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); + } + + if(!UpdateLimiterAlarm()) { + APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); + return false; + } + + if(remindTasks.size() > 0) { + APP_LOGI("%{public}s end", __func__); + return true; + } else { + APP_LOGI("%{public}s end, remindTasks is empty", __func__); + return false; + } +} +/** + * @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}" PRId64 ", 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. + * @return Returns true on success, false on failure. + */ +bool 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; + } + } + } + + if (!UpdateAtTimerAlarm()) { + APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + return false; + } + return true; + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Delete dynamic refresh item. + * @param formId The Id of the form. + */ +bool 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); + + if (!UpdateDynamicAlarm()) { + APP_LOGE("%{public}s, failed to UpdateDynamicAlarm", __func__); + return false; + } + return true; + 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__); + + APP_LOGI("%{public}s end", __func__); + return true; +} + + +/** + * @brief Clear update at timer resource. + */ +void FormTimerMgr::ClearUpdateAtTimerResource() +{ + APP_LOGI("%{public}s start", __func__); + APP_LOGI("%{public}s end", __func__); +} + +/** + * @brief Update limiter task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateLimiterAlarm() +{ + APP_LOGI("%{public}s start", __func__); + + return true; +} +/** + * @brief Clear limiter timer resource. + */ +void FormTimerMgr::ClearLimiterTimerResource() +{ + APP_LOGI("%{public}s start", __func__); + APP_LOGI("%{public}s end", __func__); +} + + +/** + * @brief Update dynamic refresh task alarm. + * @return Returns true on success, false on failure. + */ +bool FormTimerMgr::UpdateDynamicAlarm() +{ + APP_LOGI("%{public}s start", __func__); + + APP_LOGI("%{public}s end", __func__); + + return true; +} + +/** + * @brief Clear dynamic refresh resource. + */ +void FormTimerMgr::ClearDynamicResource() +{ + APP_LOGI("%{public}s start", __func__); + 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 Ensure init interval timer resource. + */ +void FormTimerMgr::EnsureInitIntervalTimer() +{ + if (intervalTimerId_ != 0L) { + return; + } + + APP_LOGI("%{public}s, init base timer task", __func__); + APP_LOGI("%{public}s end", __func__); +} +/** + * @brief Clear interval timer resource. + */ +void FormTimerMgr::ClearIntervalTimer() +{ + APP_LOGI("%{public}s start", __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_); + + intervalTimerId_ = 0L; + updateAtTimerId_ = 0L; + dynamicAlarmTimerId_ = 0L; + limiterTimerId_ = 0L; + 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..d033818a1bf2addffede4129143fa14cfb905b98 --- /dev/null +++ b/services/formmgr/src/form_util.cpp @@ -0,0 +1,191 @@ +/* + * 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 "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() +{ + char buf[256] = {0}; + 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); + uint64_t unsignedudidHash = static_cast(udidHash); + uint64_t formId = unsignedudidHash | (int32_t)(elapsedHash & 0x000000007fffffffL); + APP_LOGI("%{public}s, GenerateFormId generate formId %{public}" PRId64 "", __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(uint64_t formId, uint64_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}" PRId64 "", __func__, udidHash); + if (udidHash != INVALID_UDID_HASH) { + return true; + } + + 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}" PRId64 "", __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..5ab060b4507e3cd058f90ba026214edd74486efa --- /dev/null +++ b/services/formmgr/test/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("//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_death_callback_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..55bc225a85dfd9c4938b22da6797fb077fcb84cd --- /dev/null +++ b/services/formmgr/test/mock/include/mock_form_death_callback.h @@ -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. + */ + +#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_callback_interface.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 FormCallbackInterface { +public: + MockFormDeathCallback() = default; + virtual ~MockFormDeathCallback() = default; + + void OnDeathReceived() + { + APP_LOGI("%{public}s called.", __func__); + } + + /** + * @brief Update form. + * + * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. + */ + void ProcessFormUpdate(const FormJsInfo &formJsInfo) + { + APP_LOGI("%{public}s called.", __func__); + } + + /** + * @brief Uninstall form. + * + * @param formId Indicates the ID of the form to uninstall. + */ + void ProcessFormUninstall(const int64_t formId) + { + 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..4555049f67ee15708c5c05b90ca54422afe80d5b --- /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..92dd97e82e58d6eded8fee20138b2210fde30b46 --- /dev/null +++ b/services/formmgr/test/mock/src/mock_form_host_client.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 +#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 { + +/** + * 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..ff1e3a499a2e7743c5cb8d634840378d32da3558 --- /dev/null +++ b/services/formmgr/test/mock/src/mock_form_provider_client.cpp @@ -0,0 +1,134 @@ +/* + * 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"); + } + + 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..4416792dee3eabc4ed712d2155b47b72d8b97569 --- /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..c76f6e4c3c476e3b867bd41cd7df05a3867050e5 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp @@ -0,0 +1,2142 @@ +/* + * 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; + record.bundleName = ""; + record.moduleName = ""; + record.abilityName = ""; + record.formName = ""; + record.specification = 0; + + 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: SetFormCacheInited + * @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_APPEXECFWK_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..b91066b8351acee81e1b170c42f15f2fff1368ca --- /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_COMMON_CODE, 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..e062b3f41cd0b93b935d97aec6fcfb81ac5ac230 --- /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..1d7f2c0a86549a5644f4784fc3b1071c7389994f --- /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_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(0L, token_)); + // Caller ability token is nullptr + int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; + ASSERT_EQ(ERR_APPEXECFWK_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_APPEXECFWK_FORM_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_APPEXECFWK_FORM_OPERATION_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..0ab6a7845a3eb295280c9feb5833ee71089d8752 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_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("FmsFormMgrDeathCallbackTest") { + 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_death_callback.cpp", + "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", + ] + sources += [ "fms_form_mgr_death_callback_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 = [ ":FmsFormMgrDeathCallbackTest" ] +} 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..3b78d9aa083889c50627c54de0efea44b1b0205e --- /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..fee5463c9d5c77a913e439bd774e3bfa5d144ff9 --- /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_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(0, token_)); + // case when token is nullptr + EXPECT_EQ(ERR_APPEXECFWK_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_APPEXECFWK_FORM_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_APPEXECFWK_FORM_OPERATION_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_APPEXECFWK_FORM_COMMON_CODE, 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_APPEXECFWK_FORM_COMMON_CODE, 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..01e862d910d339eafe0170c70e175d2ccbe96dbd --- /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_APPEXECFWK_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_APPEXECFWK_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..27a72210b4dc61f1f0f7b8564e36121862bbf529 --- /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_NOT_EXIST_ID, 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_COMMON_CODE, 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_APPEXECFWK_FORM_OPERATION_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..16f74195dccb53b829eda5afecf54e57bc88c687 --- /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,318 @@ +/* + * 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); + std::vector permnameList; + permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, + permnameList, 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; + iteminfo.temporaryFlag_ = true; + 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; + iteminfo.temporaryFlag_ = true; + 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; + iteminfo.temporaryFlag_ = 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_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; + iteminfo.temporaryFlag_ = 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; + iteminfo.temporaryFlag_ = 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..b9cd43b3bb131b03759347a209b79421ba55b076 --- /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,403 @@ +/* + * 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); + std::vector permnameList; + permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); + OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, + permnameList, 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..30a5b3673c285f24401dfdcfa932f9c028a60bb1 --- /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_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(0L, token_, false)); + // sptr is nullptr + EXPECT_EQ(ERR_APPEXECFWK_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_APPEXECFWK_FORM_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_APPEXECFWK_FORM_OPERATION_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..cef35f47929c5cac8ff3c1786f6711937eb53133 --- /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_APPEXECFWK_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_APPEXECFWK_FORM_OPERATION_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..bde926b055812207a4470dfcf43484a65f5cddbf --- /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_APPEXECFWK_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_APPEXECFWK_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_APPEXECFWK_FORM_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_APPEXECFWK_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..f20fec9b9bc0b10186e0d7d008e10208b1d1814b --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp @@ -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. + */ + +#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 std::string 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); + + nlohmann::json jsonData_; +}; +void FmsFormProviderDataTest::SetUp() +{ + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR.c_str()); + if (dirptr == nullptr) { + APP_LOGW("%{public}s, opendir is fail", __func__); + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR.c_str(), 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_APPEXECFWK_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_NOT_EXIST_ID, 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_COMMON_CODE, + 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_NOT_EXIST_ID, 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_PROVIDER_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..705667c2aadaa5bcb977d4cac7344760722a60fb --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn @@ -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. + +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/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//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/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//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..d6e661b62e6006ce51257d88f0f3a24594690306 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp @@ -0,0 +1,234 @@ +/* + * 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_APPEXECFWK_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_NOT_EXIST_ID, 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; + iteminfo.temporaryFlag_ = true; + 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; + iteminfo.temporaryFlag_ = true; + FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); + + EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_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; + iteminfo.temporaryFlag_ = true; + 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; + iteminfo.temporaryFlag_ = true; + 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_APPEXECFWK_FORM_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..ef6b82067dd485bce5010185d5e564b8962a2d20 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn @@ -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. + +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/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//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/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//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..2b094e5940ea45bcfe11a965c994497da4124fa8 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp @@ -0,0 +1,474 @@ +/* + * 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_COMMON_CODE, 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..93ef619b6164f6a1b85cb4239bd27f508cfafd34 --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_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/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/", + "//base/miscservices/time/interfaces/innerkits/include", + ] + + 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", + "${services_path}/formmgr:fms_target", + "//base/miscservices/time/services:time_service", + "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", + "//base/notification/ces_standard/frameworks/common:libevent_common", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//third_party/googletest:gmock_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "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..b8c72fada0bdf4c63b64d51f83e292d832c0a0ba --- /dev/null +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_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 + +#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: HandleSystemTimeChanged. + * @tc.desc: Handle system 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); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + EXPECT_EQ(isAddOk6, 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); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0010 + * @tc.name: HandleResetLimiter. + * @tc.desc: Handle reset limiter. + */ +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, 16, 30); + EXPECT_EQ(isAddOk5, true); + bool isAddOk6 = FormTimerMgr::GetInstance().HandleResetLimiter(); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 end"; +} + +/** + * @tc.number: Fms_FormTimerMgr_0011 + * @tc.name: OnUpdateAtTrigger. + * @tc.desc:handle attimer 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); + + bool isAddOk6 = FormTimerMgr::GetInstance().OnUpdateAtTrigger(90L); + EXPECT_EQ(isAddOk6, true); + + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0011 end"; +} +/** + * @tc.number: Fms_FormTimerMgr_0012 + * @tc.name: OnDynamicTimeTrigger. + * @tc.desc: handle 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); + + bool isAddOk6 = FormTimerMgr::GetInstance().OnDynamicTimeTrigger(90L); + EXPECT_EQ(isAddOk6, 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/ability_running_record_test/ams_ability_running_record_module_test.cpp b/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp index 21555dd04739c79ae960b4230a37fa928cab6e30..0de9b540d54eb9dcb6f755c8151a651594e3f418 100644 --- a/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp +++ b/services/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp @@ -27,10 +27,8 @@ using namespace testing::ext; namespace OHOS { namespace AppExecFwk { namespace { - const std::string APP_RECORD_NAME = "App_Name_Z"; const std::string ABILITY_RECORD_NAME = "Ability_Name_Z"; - // schedule phase const int NONE_SCHEDULED = 0; const int FOREGROUND_SCHEDULED = 1 << 0; @@ -44,9 +42,7 @@ const int CLEAN_ABILITY_SCHEDULED = 1 << 7; const int PROFILE_CHANGED_SCHEDULED = 1 << 8; const int SCHEDULE_CONFIGURATION_UPDATED = 1 << 9; const int ABILITY_RUNNING_RECORD_NUM = 1000; - } // namespace - class MockedSchedulerBase { public: MockedSchedulerBase() @@ -427,6 +423,5 @@ HWTEST_F(AmsAbilityRunningRecordModuleTest, OperateAbilityRunningRecord_001, Tes } APP_LOGI("OperateAbilityRunningRecord_001 end"); } - } // namespace AppExecFwk } // namespace OHOS 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..15e0e9b4bc2590e8b01147e119a226366af1aaea 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 @@ -38,24 +38,26 @@ using testing::Return; using testing::SetArgReferee; namespace { - const int32_t ABILITY_NUM = 100; const int32_t APPLICATION_NUM = 100; const int32_t INDEX_NUM_100 = 100; const int32_t INDEX_NUM_MAX = 100; const std::string TEST_APP_NAME = "test_app_"; const std::string TEST_ABILITY_NAME = "test_ability_"; - +#define CHECK_POINTER_IS_NULLPTR(object) \ + do { \ + if (object == nullptr) { \ + return; \ + } \ + } while (0) } // namespace namespace OHOS { namespace AppExecFwk { - struct TestProcessInfo { pid_t pid = 0; bool isStart = false; }; - // specify process condition class AmsAppLifeCycleModuleTest : public testing::Test { public: @@ -216,7 +218,8 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToForegroud(const sptrUpdateAbilityState(token, AbilityState::ABILITY_STATE_FOREGROUND); if (!isChange) { - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationForegrounded(recordId); } @@ -235,7 +238,8 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToBackGroud(const sptrUpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); if (!isChange) { - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationBackgrounded(recordId); } @@ -251,7 +255,8 @@ void AmsAppLifeCycleModuleTest::ChangeAppToTerminate(const sptrAbilityTerminated(token); - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationTerminated(recordId); } else { @@ -269,11 +274,13 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToTerminate( void AmsAppLifeCycleModuleTest::CheckState(const std::shared_ptr &appRunningRecord, const sptr &token, const AbilityState abilityState, const ApplicationState appState) const { - ASSERT_NE(appRunningRecord, nullptr); + EXPECT_NE(appRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(appRunningRecord); auto abilityRunningRecord = appRunningRecord->GetAbilityRunningRecordByToken(token); ApplicationState getAppState = appRunningRecord->GetState(); EXPECT_EQ(appState, getAppState); - ASSERT_NE(abilityRunningRecord, nullptr); + EXPECT_NE(abilityRunningRecord, nullptr); + CHECK_POINTER_IS_NULLPTR(abilityRunningRecord); AbilityState getAbilityState = abilityRunningRecord->GetState(); EXPECT_EQ(abilityState, getAbilityState); } @@ -350,11 +357,6 @@ sptr AmsAppLifeCycleModuleTest::GetAbilityToken() return mockToken_; } -// void InvokeOnAbilityRequestDone(const sptr &obj, const AbilityState state) -// { -// EXPECT_EQ(state, AbilityState::ABILITY_STATE_BACKGROUND); -// } - /* * Feature: Ams * Function: AppLifeCycle @@ -371,13 +373,14 @@ sptr AmsAppLifeCycleModuleTest::GetAbilityToken() */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); pid_t pid = 1024; sptr token = GetAbilityToken(); 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; @@ -416,7 +419,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_002, TestSize.Level3) { pid_t pid = 1023; - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); std::shared_ptr appRunningRecord = nullptr; std::vector> tokens; auto abilityInfo = std::make_shared(); @@ -473,7 +477,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(); @@ -525,7 +529,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_003, TestSize.Level3) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_004, TestSize.Level3) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p3", "com.ohos.test.helloworld"); @@ -572,7 +577,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_004, TestSize.Level3) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_005, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); pid_t pid = 1024; sptr token0 = new (std::nothrow) MockAbilityToken(); @@ -635,7 +641,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_005, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); pid_t pid = fork(); if (pid == 0) { @@ -643,7 +650,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) exit(0); } - ASSERT_TRUE(pid > 0); + EXPECT_TRUE(pid > 0); usleep(50000); sptr token = GetAbilityToken(); @@ -692,7 +699,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_007, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); @@ -741,7 +749,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_007, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_008, TestSize.Level2) { - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); pid_t pid_0 = 1024; pid_t pid_1 = 2048; sptr token_0 = new (std::nothrow) MockAbilityToken(); @@ -811,7 +820,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_008, TestSize.Level2) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_009, TestSize.Level3) { pid_t pid = 1025; - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); std::shared_ptr appRunningRecord = nullptr; auto abilityInfo = std::make_shared(); auto appInfo = std::make_shared(); @@ -857,7 +867,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_009, TestSize.Level3) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_010, TestSize.Level3) { pid_t pid = 1025; - ASSERT_NE(serviceInner_, nullptr); + EXPECT_NE(serviceInner_, nullptr); + CHECK_POINTER_IS_NULLPTR(serviceInner_); std::shared_ptr appRunningRecord = nullptr; int32_t recordId[APPLICATION_NUM]; sptr mockAppScheduler[APPLICATION_NUM]; @@ -868,10 +879,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 +893,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 +977,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); @@ -979,7 +990,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_013, TestSize.Level3) EXPECT_CALL(*mockAppSpawnSocket, OpenAppSpawnConnection()).Times(1).WillOnce(Return(0)); int ret = serviceInner_->OpenAppSpawnConnection(); - ASSERT_EQ(ret, 0); + EXPECT_EQ(ret, 0); EXPECT_EQ(serviceInner_->QueryAppSpawnConnectionState(), SpawnConnectionState::STATE_CONNECTED); EXPECT_CALL(*mockAppSpawnSocket, CloseAppSpawnConnection()).Times(1); @@ -1370,6 +1381,5 @@ HWTEST_F(AmsAppLifeCycleModuleTest, AbilityBehaviorAnalysis_06, TestSize.Level0) EXPECT_EQ(abilityRecord_1->GetPerceptibility(), perceptibility); EXPECT_EQ(abilityRecord_1->GetConnectionState(), connectionState); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file 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..1b0b8039558e3c658eff7c4bc6f2a479ff1be317 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 @@ -34,13 +34,11 @@ using testing::InvokeWithoutArgs; using testing::Return; namespace { - constexpr int COUNT = 1; } namespace OHOS { namespace AppExecFwk { - class TestAppSchedulerImpl : public AppSchedulerHost { public: void ScheduleForegroundApplication() override @@ -66,7 +64,6 @@ public: void ScheduleProcessSecurityExit() override {} }; - class AppMgrServiceModuleTest : public testing::Test { public: static void SetUpTestCase(); @@ -75,9 +72,9 @@ public: void TearDown(); protected: - inline static std::shared_ptr mockAppMgrServiceInner_; - inline static std::shared_ptr appMgrService_; - inline static sptr testRemoteObject_; + inline static std::shared_ptr mockAppMgrServiceInner_{nullptr}; + inline static std::shared_ptr appMgrService_{nullptr}; + inline static sptr testRemoteObject_{nullptr}; }; void AppMgrServiceModuleTest::SetUpTestCase() @@ -139,9 +136,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 +161,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 +195,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 +229,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 +263,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 +297,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 +331,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 +367,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 +407,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 +443,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,12 +474,11 @@ HWTEST_F(AppMgrServiceModuleTest, QueryServiceState_001, TestSize.Level1) */ HWTEST_F(AppMgrServiceModuleTest, GetAmsMgr_001, TestSize.Level1) { - ASSERT_TRUE(appMgrService_); + EXPECT_TRUE(appMgrService_); auto amsMgr = appMgrService_->GetAmsMgr(); EXPECT_TRUE(amsMgr); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp b/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp index a9640bc1684bb4b3f65c33cbc5a8b7ea5f6ec5ea..18f6aee531c9219391723362203d07ea1468b2a4 100644 --- a/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp +++ b/services/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp @@ -36,14 +36,12 @@ using testing::SetArgReferee; namespace OHOS { namespace AppExecFwk { namespace { - const int32_t INDEX_NUM_1 = 1; const int32_t INDEX_NUM_2 = 2; const int32_t INDEX_NUM_3 = 3; const int32_t INDEX_NUM_10 = 10; const std::string TEST_APP_NAME = "test_app_"; const std::string TEST_ABILITY_NAME = "test_ability_"; - } // namespace class AmsAppRecentListModuleTest : public testing::Test { @@ -58,9 +56,9 @@ protected: const std::shared_ptr CreateAppRunningRecordByIndex(const int32_t index) const; void CreateAppRecentList(const int32_t appNum); - std::unique_ptr serviceInner_; - sptr mockToken_; - sptr mockBundleMgr; + std::unique_ptr serviceInner_{nullptr}; + sptr mockToken_{nullptr}; + sptr mockBundleMgr{nullptr}; }; void AmsAppRecentListModuleTest::SetUpTestCase() @@ -331,6 +329,5 @@ HWTEST_F(AmsAppRecentListModuleTest, Clear_Recent_List_001, TestSize.Level0) EXPECT_TRUE(serviceInner_->GetRecentAppList().empty()); APP_LOGI("Clear_Recent_List_002 end"); } - } // namespace AppExecFwk } // namespace OHOS 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..3f79fc7602094d518596da9d876cc6ae19c3cb45 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 @@ -35,7 +35,6 @@ using testing::InvokeWithoutArgs; namespace OHOS { namespace AppExecFwk { - class AmsAppRunningRecordModuleTest : public testing::Test { public: static void SetUpTestCase(); @@ -63,7 +62,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 +91,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,14 +110,14 @@ 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!"; EXPECT_EQ(abilityName, abilityNameFromServ) << "fail, app record name is not equal!"; } - std::unique_ptr service_; + std::unique_ptr service_{nullptr}; sptr GetMockToken() const { @@ -127,10 +126,20 @@ protected: private: std::vector appName_ = { - "test_app_name1", "test_app_name2", "test_app_name3", "test_app_name4", "test_app_name5"}; + "test_app_name1", + "test_app_name2", + "test_app_name3", + "test_app_name4", + "test_app_name5", + }; std::vector abilityName_ = { - "test_ability_name1", "test_ability_name2", "test_ability_name3", "test_ability_name4", "test_ability_name5"}; - sptr mockToken_; + "test_ability_name1", + "test_ability_name2", + "test_ability_name3", + "test_ability_name4", + "test_ability_name5", + }; + sptr mockToken_{nullptr}; }; void AmsAppRunningRecordModuleTest::SetUpTestCase() @@ -170,8 +179,8 @@ 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!"; - ASSERT_FALSE(result.appExists) << ",result is wrong!"; + EXPECT_TRUE(record != nullptr) << ",create apprunningrecord fail!"; + EXPECT_FALSE(result.appExists) << ",result is wrong!"; // check apprunningrecord int32_t id = record->GetRecordId(); @@ -196,7 +205,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,8 +239,8 @@ 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!"; - ASSERT_FALSE(result.appExists) << "result is wrong!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_FALSE(result.appExists) << "result is wrong!"; // check abilityrunningrecord & apprunningrecord int32_t id = record->GetRecordId(); @@ -262,7 +271,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,8 +282,8 @@ 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!"; - ASSERT_FALSE(result.appExists) << "result is wrong!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication sptr mockApplication(new MockApplication()); @@ -310,7 +319,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,8 +330,8 @@ 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!"; - ASSERT_FALSE(result.appExists) << "result is wrong!"; + EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; + EXPECT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication sptr mockApplication(new MockApplication()); @@ -358,7 +367,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 +381,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 +437,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 +448,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()); @@ -472,6 +481,5 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStatusChange_006, TestSize.Le auto stateFromRec = record->GetState(); EXPECT_EQ(stateFromRec, ApplicationState::APP_STATE_TERMINATED); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp b/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp index 46881ed2c4b7c4f7f0c8def6657a1f810ef3fdb5..72d43e9e373915965733980e0305222f13d8f944 100644 --- a/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp +++ b/services/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp @@ -34,11 +34,8 @@ using testing::SetArgReferee; namespace OHOS { namespace AppExecFwk { namespace { - const uint32_t CYCLE_NUMBER = 10; - } // namespace - struct TestApplicationPreRunningRecord { TestApplicationPreRunningRecord( const std::shared_ptr &appRecord, const sptr &mockAppScheduler) @@ -64,7 +61,6 @@ struct TestApplicationPreRunningRecord { }; pid_t TestApplicationPreRunningRecord::g_pid = 0; - class AmsAppServiceFlowModuleTest : public testing::Test { public: static void SetUpTestCase(); @@ -78,7 +74,7 @@ protected: const std::string &appName, const AbilityState abilityState, const ApplicationState appState) const; protected: - std::shared_ptr serviceInner_; + std::shared_ptr serviceInner_ = nullptr; std::shared_ptr handler_ = nullptr; }; @@ -714,6 +710,5 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOnAndOff_001, TestSize.L EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppA.appRecord_->GetState()); APP_LOGI("AmsAppServiceFlowModuleTest ServiceFlow_ScreenOnAndOff_001 end"); } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp index 9fc352a18152bd2cc48c00370ea793b47740e1a9..fb70baede03e7fa4217ed38113e6394e9754d536 100644 --- a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp @@ -41,13 +41,9 @@ using testing::InvokeWithoutArgs; namespace OHOS { namespace AppExecFwk { - namespace { - const int32_t COUNT = 1000; - } // namespace - class AmsIpcAmsmgrModuleTest : public testing::Test { public: static void SetUpTestCase(); @@ -69,11 +65,11 @@ public: protected: sptr mockToken_ = nullptr; - sptr token_; - std::unique_ptr client_; + sptr token_{nullptr}; + std::unique_ptr client_{nullptr}; - std::shared_ptr mockAppMgrServiceInner_; - std::shared_ptr amsEventHandler_; + std::shared_ptr mockAppMgrServiceInner_{nullptr}; + std::shared_ptr amsEventHandler_{nullptr}; }; class MockMockAppMgrService : public MockAppMgrService { @@ -422,6 +418,5 @@ HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_007, TestSize.Level3) mockAppMgrServiceInner.reset(); amsMgrScheduler.release(); } - } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/common/ams/ipc_app_mgr_test/ams_ipc_app_mgr_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_mgr_test/ams_ipc_app_mgr_module_test.cpp index 58a7556eda78fbeb48dbae368981d926683f81d4..caf863ae46c4cccec695e057ebdae030fd3392e9 100644 --- a/services/test/moduletest/common/ams/ipc_app_mgr_test/ams_ipc_app_mgr_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_app_mgr_test/ams_ipc_app_mgr_module_test.cpp @@ -32,13 +32,9 @@ using OHOS::sptr; using testing::_; using testing::Invoke; using testing::InvokeWithoutArgs; - namespace { - const int32_t COUNT = 10000; - } // namespace - class AmsIpcAppmgrModuleTest : public testing::Test { public: static void SetUpTestCase(); diff --git a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp index 356d2ba86ee67b79c248a662f2c1dcfe69898e2c..bba642f874d729bb198625cdd1a59117cd044b48 100644 --- a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp @@ -31,11 +31,8 @@ using testing::Invoke; using testing::InvokeWithoutArgs; namespace { - const int32_t COUNT = 10000; - } // namespace - class AmsIpcAppSchedulerModuleTest : public testing::Test { public: static void SetUpTestCase(); @@ -265,7 +262,7 @@ HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_008, TestSi mockApplication->Wait(); bool isEqual = mockApplication->CompareAppLaunchData(launchData); - ASSERT_EQ(true, isEqual) << "excute fail, index is " << i; + EXPECT_EQ(true, isEqual) << "excute fail, index is " << i; } } diff --git a/services/test/moduletest/common/ams/process_optimizer_uba_test/ams_process_optimizer_uba_module_test.cpp b/services/test/moduletest/common/ams/process_optimizer_uba_test/ams_process_optimizer_uba_module_test.cpp index 699685fde8cf88f26e933dadd2c369e8780e4907..cfb2dd1891f157788fec7582de88b4e25b2b6095 100644 --- a/services/test/moduletest/common/ams/process_optimizer_uba_test/ams_process_optimizer_uba_module_test.cpp +++ b/services/test/moduletest/common/ams/process_optimizer_uba_test/ams_process_optimizer_uba_module_test.cpp @@ -21,6 +21,10 @@ #include #include "app_log_wrapper.h" +using namespace testing::ext; +namespace OHOS { +namespace AppExecFwk { +namespace { const std::string APP_RECORD_NAME = "App_Name_Z"; // foreground process oom_adj constexpr int APP_OOM_ADJ_FOREGROUND = 0; @@ -31,13 +35,8 @@ constexpr int APP_OOM_ADJ_SUSPEND_MIN = 600; static constexpr int APP_SUSPEND_TIMEOUT_DEFAULT = 100; static constexpr int APP_USLEEP = 200 * 1000; - -using namespace testing::ext; - -namespace OHOS { -namespace AppExecFwk { - -class ProcessOptimizerModuleTest : public testing::Test { +} // namespace +class AmsProcessOptimizerUbaModuleTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); @@ -50,7 +49,7 @@ public: std::make_unique(nullptr, nullptr, APP_SUSPEND_TIMEOUT_DEFAULT); }; -void ProcessOptimizerModuleTest::SuspendApplication(const std::shared_ptr &appRecord) +void AmsProcessOptimizerUbaModuleTest::SuspendApplication(const std::shared_ptr &appRecord) { if (!appRecord) { APP_LOGE("app record is null"); @@ -65,7 +64,7 @@ void ProcessOptimizerModuleTest::SuspendApplication(const std::shared_ptrOnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND); } -void ProcessOptimizerModuleTest::ResumeApplication(const std::shared_ptr &appRecord) +void AmsProcessOptimizerUbaModuleTest::ResumeApplication(const std::shared_ptr &appRecord) { if (!appRecord) { APP_LOGE("app record is null"); @@ -77,16 +76,16 @@ void ProcessOptimizerModuleTest::ResumeApplication(const std::shared_ptrGetUid()); } -void ProcessOptimizerModuleTest::SetUpTestCase() +void AmsProcessOptimizerUbaModuleTest::SetUpTestCase() {} -void ProcessOptimizerModuleTest::TearDownTestCase() +void AmsProcessOptimizerUbaModuleTest::TearDownTestCase() {} -void ProcessOptimizerModuleTest::SetUp() +void AmsProcessOptimizerUbaModuleTest::SetUp() {} -void ProcessOptimizerModuleTest::TearDown() +void AmsProcessOptimizerUbaModuleTest::TearDown() {} /* @@ -96,9 +95,9 @@ void ProcessOptimizerModuleTest::TearDown() * FunctionPoints: add application * CaseDescription: Call the OnAppAdded function to add multiple application */ -HWTEST_F(ProcessOptimizerModuleTest, OnAppAdded_001, TestSize.Level1) +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppAdded_001, TestSize.Level1) { - APP_LOGI("ProcessOptimizerModuleTest OnAppAdded_001 start"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppAdded_001 start"); bool isSuccess = processOptimizerUBA->Init(); EXPECT_TRUE(true == isSuccess); @@ -125,7 +124,7 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppAdded_001, TestSize.Level1) oomAdj1 = priorityObject1->GetCurAdj(); - APP_LOGI("ProcessOptimizerModuleTest OnAppAdded_001 end"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppAdded_001 end"); } /* @@ -135,9 +134,9 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppAdded_001, TestSize.Level1) * FunctionPoints: change application status * CaseDescription: Set a different state, check the value of adj */ -HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_001, TestSize.Level1) +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppStateChanged_001, TestSize.Level1) { - APP_LOGI("ProcessOptimizerModuleTest OnAppStateChanged_001 start"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_001 start"); bool isSuccess = processOptimizerUBA->Init(); EXPECT_TRUE(true == isSuccess); @@ -155,7 +154,7 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_001, TestSize.Level1) auto oomAdj = priorityObject->GetCurAdj(); EXPECT_TRUE(oomAdj == APP_OOM_ADJ_FOREGROUND); - APP_LOGI("ProcessOptimizerModuleTest OnAppStateChanged_001 end"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_001 end"); } /* @@ -165,9 +164,9 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_001, TestSize.Level1) * FunctionPoints: change application status * CaseDescription: Set a different state, check the value of adj */ -HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_002, TestSize.Level1) +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppStateChanged_002, TestSize.Level1) { - APP_LOGI("ProcessOptimizerModuleTest OnAppStateChanged_002 start"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_002 start"); bool isSuccess = processOptimizerUBA->Init(); EXPECT_TRUE(true == isSuccess); @@ -186,7 +185,7 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_002, TestSize.Level1) auto oomAdj = priorityObject->GetCurAdj(); EXPECT_TRUE(oomAdj == APP_OOM_ADJ_BACKGROUND_MIN); - APP_LOGI("ProcessOptimizerModuleTest OnAppStateChanged_002 end"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_002 end"); } /* @@ -198,14 +197,14 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_002, TestSize.Level1) function, make the app state suspended 2. Call the OnAppStateChanged function to remove the suspended state */ -HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_003, TestSize.Level1) +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppStateChanged_003, TestSize.Level1) { - APP_LOGI("ProcessOptimizerModuleTest OnAppStateChanged_003 start"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_003 start"); processOptimizerUBA->AppSuspended = - std::bind(&ProcessOptimizerModuleTest::SuspendApplication, this, std::placeholders::_1); + std::bind(&AmsProcessOptimizerUbaModuleTest::SuspendApplication, this, std::placeholders::_1); processOptimizerUBA->AppResumed = - std::bind(&ProcessOptimizerModuleTest::ResumeApplication, this, std::placeholders::_1); + std::bind(&AmsProcessOptimizerUbaModuleTest::ResumeApplication, this, std::placeholders::_1); bool isSuccess = processOptimizerUBA->Init(); EXPECT_TRUE(true == isSuccess); @@ -226,7 +225,7 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_003, TestSize.Level1) auto oomAdj = priorityObject->GetCurAdj(); EXPECT_TRUE(oomAdj == APP_OOM_ADJ_SUSPEND_MIN); - GTEST_LOG_(INFO) << "ProcessOptimizerModuleTest OnAppStateChanged_003 oomAdj: " << oomAdj; + GTEST_LOG_(INFO) << "AmsProcessOptimizerUbaModuleTest OnAppStateChanged_003 oomAdj: " << oomAdj; auto appState = app->GetState(); if (appState == ApplicationState::APP_STATE_SUSPENDED) { @@ -236,7 +235,7 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_003, TestSize.Level1) EXPECT_TRUE(oomAdj == APP_OOM_ADJ_BACKGROUND_MIN); } - APP_LOGI("ProcessOptimizerModuleTest OnAppStateChanged_003 end"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppStateChanged_003 end"); } /* @@ -248,9 +247,9 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppStateChanged_003, TestSize.Level1) function 2. Calling the OnAppRemoved function will call the StopAppSuspendTimer function */ -HWTEST_F(ProcessOptimizerModuleTest, OnAppRemoved_001, TestSize.Level1) +HWTEST_F(AmsProcessOptimizerUbaModuleTest, OnAppRemoved_001, TestSize.Level1) { - APP_LOGI("ProcessOptimizerModuleTest OnAppRemoved_001 start"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppRemoved_001 start"); bool isSuccess = processOptimizerUBA->Init(); EXPECT_TRUE(true == isSuccess); @@ -274,7 +273,7 @@ HWTEST_F(ProcessOptimizerModuleTest, OnAppRemoved_001, TestSize.Level1) EXPECT_TRUE(oomAdj == APP_OOM_ADJ_BACKGROUND_MIN); - APP_LOGI("ProcessOptimizerModuleTest OnAppRemoved_001 end"); + APP_LOGI("AmsProcessOptimizerUbaModuleTest OnAppRemoved_001 end"); } } // namespace AppExecFwk diff --git a/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp index d50d759ce6af828b33b0fb0ccc08996f93330180..22657286d361b9ffa5dc435f8cf46398f2417b07 100644 --- a/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp +++ b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp @@ -40,11 +40,9 @@ using testing::Invoke; using testing::Return; namespace { - const uint32_t CYCLE_NUMBER = 10; const int32_t PID_VALUE = 13579; const int32_t CONNECT_RETRY_MAX_TIMES = 15; - } // namespace // this function is only used to mock sleep method so mst can run without delay. @@ -208,8 +206,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_001, TestSize for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); appMgrService->OnStart(); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStop(); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); @@ -243,8 +241,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_002, TestSize EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); MockedAppSpawnSocket::gConnectSuccess_ = true; appMgrService->OnStart(); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStop(); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); @@ -270,8 +268,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_003, TestSize for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); appMgrService->OnStart(); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStart(); EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); diff --git a/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp b/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp index ae18a39701f746fb3b71798c20dfa957c46a0ce8..2f0de0cbccfb4036cc73b8c4ea8110e37541c282 100644 --- a/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp +++ b/services/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp @@ -28,11 +28,8 @@ using namespace OHOS::AppExecFwk; using OHOS::Semaphore; namespace { - const uint32_t CYCLE_NUMBER = 10000; - } - enum class AmsInnerState { STATE_NO_OPERATION, STATE_ABILITY_LOADED, 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..53e88c5284af87fd6eba22b2a82c70a980eeab17 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 @@ -26,9 +26,7 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; namespace { - const int CYCLE_NUMBER = 10000; - } // namespace class AppMgrServiceInnerMock : public AppMgrServiceInner { @@ -71,7 +69,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 +96,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 42541c91d2e41f107024f433c9af9563645e72ef..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", @@ -225,7 +228,7 @@ protected: }, "baseBundleInfo": { "abilityInfos": [], - "appId": "", + "appId": "BNtg4JBClbl92Rgc3jm/RfcAdrHXaM8F0QOiwVEhnV5ebE5jNIYnAx+weFRT3QTyUjRNdhmc2aAzWyi+5t5CoBM=", "applicationInfo": { "bundleName": "", "cacheDir": "", @@ -348,7 +351,6 @@ protected: "isKeepData": false, "isSupportBackup": false, "mainAbility": "com.ohos.launchercom.ohos.launchercom.ohos.launcher.MainAbility", - "provisionId": "BNtg4JBClbl92Rgc3jm/RfcAdrHXaM8F0QOiwVEhnV5ebE5jNIYnAx+weFRT3QTyUjRNdhmc2aAzWyi+5t5CoBM=", "skillInfos": { "com.ohos.launchercom.ohos.launcher.recentscom.ohos.launcher.recents.MainAbility": [], "com.ohos.launchercom.ohos.launchercom.ohos.launcher.MainAbility": [ @@ -398,7 +400,7 @@ protected: "name": "originWidgetName", "value": "com.weather.testWidget" } - ] + ] } ] }, @@ -518,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"; } } @@ -531,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"; } } @@ -627,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); } } @@ -666,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; @@ -690,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++) { @@ -719,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; @@ -753,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; @@ -777,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; @@ -799,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; @@ -827,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); @@ -842,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); @@ -851,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); } @@ -866,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); } @@ -894,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"; @@ -915,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); } @@ -933,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; @@ -969,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(); @@ -995,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; @@ -1018,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; @@ -1053,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; @@ -1090,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 = {}; @@ -1108,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; @@ -1129,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 = {}; @@ -1147,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; @@ -1169,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 = {}; @@ -1187,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; @@ -1208,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"}; @@ -1226,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; @@ -1247,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"}; @@ -1265,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; @@ -1286,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"}; @@ -1304,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; @@ -1326,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"}; @@ -1344,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; @@ -1365,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"}; @@ -1383,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; @@ -1404,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"}; @@ -1422,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; @@ -1457,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); @@ -1468,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) { @@ -1486,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!!!"; } } @@ -1509,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); } @@ -1523,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) { @@ -1536,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!!!"; } } @@ -1554,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; @@ -1580,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/services/test/moduletest/utils/src/common_tool.cpp b/services/test/moduletest/utils/src/common_tool.cpp index 08edfb2aee15969ffabb130313504da8066318b0..f3e851a738ca0b9609b02f810d46237da37931de 100644 --- a/services/test/moduletest/utils/src/common_tool.cpp +++ b/services/test/moduletest/utils/src/common_tool.cpp @@ -99,6 +99,11 @@ bool CommonTool::CopyTmpFileToSystemPath(const std::string &srcPath, const std:: long CommonTool::GetFileBuildTime(const std::string &path) { long buildTime = 0; + + if (!CheckFilePathISExist(path)) { + return buildTime; + } + struct stat buf; FILE *file = fopen(path.c_str(), "r"); if (file == nullptr) { 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/amsKitSTAbilityManager.hap b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManager.hap index 2b3c756af72cf0fa4f6ec949a4a0a7b0f2c3d46d..75bc00b79157494efbc99860fb222a55f01c70eb 100644 Binary files a/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManager.hap and b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManager.hap differ diff --git a/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManagerFirst.hap b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManagerFirst.hap new file mode 100644 index 0000000000000000000000000000000000000000..8ca69be85181b37fdfd829453ba6f7d523db134f Binary files /dev/null and b/test/resource/ams/ams_page_ability_bundle/amsKitSTAbilityManagerFirst.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..b541b54ea04a535d4f41f950283a08821faed033 100644 --- a/test/resource/amssystemtestability/abilitySrc/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/BUILD.gn @@ -15,10 +15,14 @@ group("ams_system_test_app") { deps = [ "amsAbilityAppendTestA:amsAbilityAppendTestA", "amsAbilityAppendTestB:amsAbilityAppendTestB", + "amsAbilityVisibleTestPageA:amsAbilityVisibleTestPageA", + "amsAbilityVisibleTestServiceB:amsAbilityVisibleTestServiceB", + "amsConfigurationUpdatedTest:amsConfigurationUpdatedTest", "amsDataSystemTestA:amsDataSystemTestA", "amsDataSystemTestB:amsDataSystemTestB", "amsDataSystemTestC:amsDataSystemTestC", "amsKitSTAbilityManager:amsKitSTAbilityManager", + "amsKitSTAbilityManagerFirst:amsKitSTAbilityManagerFirst", "amsKitSystemTest:amsKitSystemTest", "amsKitSystemTestA:amsKitSystemTestA", "amsKitSystemTestB:amsKitSystemTestB", @@ -26,6 +30,8 @@ group("ams_system_test_app") { "amsKitSystemTestDataB:amsKitSystemTestDataB", "amsKitSystemTestPageA:amsKitSystemTestPageA", "amsKitSystemTestService:amsKitSystemTestService", + "amsMissionStackTest:amsMissionStackTest", + "amsMissionStackTestSubsidiary:amsMissionStackTestSubsidiary", "amsSystemTestA:amsSystemTestA", "amsSystemTestB:amsSystemTestB", "amsSystemTestC:amsSystemTestC", @@ -47,11 +53,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..d9fbfd025ba42dcaefc29b825397d21fdbcea7c5 --- 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\"", @@ -55,7 +56,10 @@ ohos_shared_library("amsAbilityAppendTestA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", ] external_deps = [ diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp index 0ee77556032cf9665bdb9fdb11d577b6b4a88e10..ddf4f31b1c5d4c17320e23d0015f1a48c671fd94 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 0; +constexpr int numTwo = 0; +constexpr int numThree = 0; +} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -110,11 +116,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp index 74d9768f8a42a4b3cc9f4e70f2cbcb85330f1a98..5f2c2f219d1a598edb0d12bce40b80eeb1d6e6ba 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 0; +constexpr int numTwo = 0; +constexpr int numThree = 0; +} void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -127,11 +133,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) 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) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( 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()}; + 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/amsAbilityAppendTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn old mode 100644 new mode 100755 index 1dbdeec9359c42df680da5e7c22c8956fddb8120..c510161b409741c5ed49b41194b4706022a31b73 --- 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\"", @@ -54,7 +55,10 @@ ohos_shared_library("amsAbilityAppendTestB") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//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/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp index db038f3117a282e90f5ef9b2e9c5681325531547..beacde5933001025b9204907d18c062ec74bb9ec 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 0; +constexpr int numTwo = 0; +constexpr int numThree = 0; +} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -103,11 +109,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRSTB.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( 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()}; + 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/amsAbilityVisibleTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..770dabb0871571189d1d36d7b69ce040d5c7d773 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn @@ -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. +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/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//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", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + 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..b3015819c5ad703b5f52f1f0be433954186f2475 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea1.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_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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.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..739a073841d08777398d4f7cdec8ab7c8e3141e0 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea2.h @@ -0,0 +1,106 @@ +/* + * 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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.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..57876df1e56b2a190750502328a41ef9a34e03c8 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea3.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_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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.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..96558792a672ad7351f6f1bbb6fabb213ffc6ca5 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/include/amsabilityvisibletestpagea4.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_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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.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..0c0e041b426fa9634a1ee7baf65b51dd4302e683 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp @@ -0,0 +1,151 @@ +/* + * 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 { +using namespace OHOS::NativeRdb; +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()); + NativeRdb::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..4382a866873f2b62b1a791641a5f8f3cfa0b6e96 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.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 "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()); + NativeRdb::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..80eedc686d0d9f923963bf1ea6b9ec008e78f3bf --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.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 "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()); + NativeRdb::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..fad9868758e94937d543a1256f19139493f48b1a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.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 "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()); + NativeRdb::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..4fc83075c951c23b6fe435fdc1b8c93a3469fd3a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn @@ -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. +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/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", + "//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", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] + 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..f8bc3ed10402095f5756483e63bc9627b7515cb6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestdata.h @@ -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. + */ + +#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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "data_ability_predicates.h" +#include "values_bucket.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 NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, + const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query(const Uri &uri, + const std::vector &columns, const NativeRdb::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..8fd85885c4bc03f32cd5b955cf79376c2afd8759 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb1.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_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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_predicates.h" +#include "values_bucket.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..fe4b3d205b7b21b90455305c9dea3e399927a401 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestpageb2.h @@ -0,0 +1,108 @@ +/* + * 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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "completed_callback.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" +#include "want_agent_helper.h" + +namespace OHOS { +namespace AppExecFwk { + +using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; +using Uri = OHOS::Uri; +using CompletedCallback = OHOS::Notification::WantAgent::CompletedCallback; +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..62393926817ce7a01fd69a8e39459ec06da62f73 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservice.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 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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "data_ability_predicates.h" +#include "values_bucket.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..32af37edd896e1f704662d11cb37c9873bae9f16 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/include/amsabilityvisibletestservicea1.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 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 "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "data_ability_predicates.h" +#include "values_bucket.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..fae0811bf061b59f4d32c69992c1bf2c55b88934 --- /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 NativeRdb::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 NativeRdb::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 NativeRdb::ValuesBucket &value, const NativeRdb::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 NativeRdb::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..9628f96aa38ccd0972c31bb1e55e813fbadae17d --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp @@ -0,0 +1,151 @@ +/* + * 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()); + NativeRdb::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..29980123edf60bf455a1704a4e7ec2215bbc7c1f --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp @@ -0,0 +1,182 @@ +/* + * 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()); + NativeRdb::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..7ada477f7757b295ca6bbd285def5e1f7ba30fc3 --- /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()); + NativeRdb::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..fdcd9bbad3f8e5f3a524a903d3a20a4d9acce4c4 --- /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()); + NativeRdb::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..84e3854bfd46979008650ff13d25652f57ab8166 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fifth_ability.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 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" + +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); + + FifthAbility() + { + mapCase_ = {}; + } + + 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_ = {}; + 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..2cafdf37ba9bb9ce2ae7a150bdbf9f7908e09379 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/fourth_ability.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 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" + +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); + + FourthAbility() + { + mapCase_ = {}; + } + + 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_ = {}; + 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..673733b01124d62ace4e3a64d760b034741ef91a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/main_ability.h @@ -0,0 +1,77 @@ +/* + * 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" + +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); + + MainAbility() + { + mapCase_ = {}; + } + + 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_ = {}; + 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..7fb04f0dc6c8c19d281382c2f7b10be404a1bc5c --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/second_ability.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 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" + +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_ = {}; + } + + 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_ = {}; + 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..bf75d349307f48c0d2ca39c4aa8ee6b71d048988 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/sixth_ability.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 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" + +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); + + SixthAbility() + { + mapCase_ = {}; + } + + 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_ = {}; + 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..24ea70115eba2c080b032cdf3a0e616b28a92f07 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/include/third_ability.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 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" + +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); + + ThirdAbility() + { + mapCase_ = {}; + } + + 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_ = {}; + 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..2d00be79bf8ec6bd3b61f104c22efed66cdb46d4 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fifth_ability.cpp @@ -0,0 +1,134 @@ +/* + * 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(); +} + +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); + } + } +} + +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..7f4fdcd25e91fdd37ecce12f102d68a5e1e32034 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/fourth_ability.cpp @@ -0,0 +1,134 @@ +/* + * 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(); +} + +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); + } + } +} + +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..fcdd089779d44928f373fc4604649afd7777ccfe --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/main_ability.cpp @@ -0,0 +1,134 @@ +/* + * 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(); +} + +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); + } + } +} + +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..bdc1df056b111a7d65acc8974033aad5fe05a24a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/second_ability.cpp @@ -0,0 +1,134 @@ +/* + * 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(); +} + +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); + } + } +} + +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..7a139ebd14f555f77b2fdf775d2cd40d08432c58 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/sixth_ability.cpp @@ -0,0 +1,133 @@ +/* + * 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(); +} + +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); + } + } +} + +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..3e75bdf815379f71af430ad9d5c979da62400675 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/test_utils.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 "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..b15f3e21b415e1e4ce0bc37358fc6153e595080e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsConfigurationUpdatedTest/src/third_ability.cpp @@ -0,0 +1,134 @@ +/* + * 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(); +} + +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); + } + } +} + +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..e8c4d9a4b524a5161c47551d7ecbb26c2dfd430c --- 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\"", @@ -56,13 +57,19 @@ ohos_shared_library("amsDataSystemTestA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//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", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", ] subsystem_name = "amssystemtestability" } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h index 46d8d51c78e3edc2ab0fbd06f94471464d4c8f27..48f930a9e3d2472c463a19215eb59b0afd6a5aa1 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/include/ams_st_data_ability_data_a.h @@ -22,6 +22,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -40,11 +43,11 @@ public: 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp index d20ed6adc089dbdbd7289d59c0884e279cbd6362..c533fdb5adf76222cc862154cf9a9c2534e3ee56 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp @@ -25,6 +25,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_A_CODE = 210; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -38,6 +39,8 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} bool AmsStDataAbilityDataA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -92,7 +95,7 @@ void AmsStDataAbilityDataA::OnStart(const Want &want) PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "OnStart"); } -int AmsStDataAbilityDataA::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStDataAbilityDataA::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStDataAbilityDataA <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "Insert"); @@ -105,22 +108,22 @@ int AmsStDataAbilityDataA::Insert(const Uri &uri, const ValuesBucket &value) return DEFAULT_INSERT_RESULT; } -int AmsStDataAbilityDataA::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataA::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataA <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "Delete"); return DEFAULT_DELETE_RESULT; } -int AmsStDataAbilityDataA::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataA::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataA <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStDataAbilityDataA::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStDataAbilityDataA::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStDataAbilityDataA <<<>>>"); @@ -129,7 +132,9 @@ std::shared_ptr AmsStDataAbilityDataA::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_A_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -137,7 +142,7 @@ std::vector AmsStDataAbilityDataA::GetFileTypes(const Uri &uri, con { APP_LOGI("AmsStDataAbilityDataA <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_A_CODE, "GetFileTypes"); - std::vector fileType{ + std::vector fileType { "filetypes", }; return fileType; @@ -161,8 +166,8 @@ int AmsStDataAbilityDataA::OpenFile(const Uri &uri, const std::string &mode) static void GetResult(std::shared_ptr child, std::shared_ptr helper, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -172,8 +177,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -187,9 +196,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } @@ -198,7 +208,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void DataTestDataAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("DataTestDataAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); for (auto child : allOperator.GetChildOperator()) { APP_LOGI("---------data--------targetBundle:%{public}s", child->GetBundleName().c_str()); diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp index 4e78eae2eb880e425b9866caedfa561c76dc5553..0955f8948aa4db6c20b2926596b4732e2095c0ca 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp @@ -20,12 +20,13 @@ #include "app_log_wrapper.h" #include "data_ability_helper.h" -#include "dummy_data_ability_predicates.h" -#include "dummy_result_set.h" -#include "dummy_values_bucket.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_A_CODE = 110; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -33,6 +34,8 @@ static const std::string OPERATOR_UPDATE = "Update"; static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; +constexpr int charCnt = 5; +} bool AmsStDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -69,7 +72,7 @@ AmsStDataAbilityPageA::~AmsStDataAbilityPageA() void AmsStDataAbilityPageA::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -132,7 +135,7 @@ void AmsStDataAbilityPageA::OnBackground() void AmsStDataAbilityPageA::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -148,8 +151,8 @@ void AmsStDataAbilityPageA::GetWantInfo(const Want &want) static void GetResult(std::shared_ptr child, std::shared_ptr helper, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -159,8 +162,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -176,9 +183,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } @@ -187,7 +195,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void DataTestPageAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("DataTestPageAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); for (auto child : allOperator.GetChildOperator()) { APP_LOGI("-----------------targetBundle:%{public}s", child->GetBundleName().c_str()); 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..2bf6c1e9c927f49900ed57727bf110ff2058948e --- 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\"", @@ -55,13 +56,19 @@ ohos_shared_library("amsDataSystemTestB") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//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", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", ] subsystem_name = "amssystemtestability" } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_data_b.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_data_b.h index 0addc8c3765fcdfd8015ba88ce73e98f59bed919..a3ef18cfd43af7177bd2d9ba6dd9ad7fd9e83df8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_data_b.h +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/include/ams_st_data_ability_data_b.h @@ -22,6 +22,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -38,11 +41,11 @@ public: 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp index cf5edc7b80c20053227de433639a4aee6b110348..665663d6a91f4d03aad9b9d3dbf9de3e03d0118c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_B_CODE = 220; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -36,6 +37,8 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} bool AmsStDataAbilityDataB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -90,29 +93,29 @@ void AmsStDataAbilityDataB::OnStart(const Want &want) PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "OnStart"); } -int AmsStDataAbilityDataB::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStDataAbilityDataB::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "Insert"); return DEFAULT_INSERT_RESULT; } -int AmsStDataAbilityDataB::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataB::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "Delete"); return DEFAULT_DELETE_RESULT; } -int AmsStDataAbilityDataB::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataB::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStDataAbilityDataB::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStDataAbilityDataB::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStDataAbilityDataB <<<>>>"); @@ -121,7 +124,9 @@ std::shared_ptr AmsStDataAbilityDataB::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_B_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -129,7 +134,7 @@ std::vector AmsStDataAbilityDataB::GetFileTypes(const Uri &uri, con { APP_LOGI("AmsStDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_B_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -149,8 +154,8 @@ int AmsStDataAbilityDataB::OpenFile(const Uri &uri, const std::string &mode) static void GetResult(std::shared_ptr child, std::shared_ptr helper, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -160,8 +165,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -175,9 +184,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } @@ -186,7 +196,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void DataTestDataBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("DataTestDataBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp index 2a48fa711c33edbeb643fcb8cbffcff4cc28e75f..c4be0f52427ae2f50f0989bbb960283051ec4cc2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp @@ -20,12 +20,14 @@ #include "app_log_wrapper.h" #include "data_ability_helper.h" -#include "dummy_data_ability_predicates.h" -#include "dummy_result_set.h" -#include "dummy_values_bucket.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" + namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_B_CODE = 120; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -33,6 +35,8 @@ static const std::string OPERATOR_UPDATE = "Update"; static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; +constexpr int charCnt = 5; +} bool AmsStDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -69,7 +73,7 @@ AmsStDataAbilityPageB::~AmsStDataAbilityPageB() void AmsStDataAbilityPageB::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -134,7 +138,7 @@ void AmsStDataAbilityPageB::OnBackground() void AmsStDataAbilityPageB::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -150,8 +154,8 @@ void AmsStDataAbilityPageB::GetWantInfo(const Want &want) static void GetResult(std::shared_ptr child, std::shared_ptr helper, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -161,8 +165,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -176,9 +184,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } @@ -187,7 +196,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void DataTestPageBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("DataTestPageBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { 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..f81cf8d1b86a950dad16b417f15467d705ae9949 --- 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\"", @@ -55,13 +56,19 @@ ohos_shared_library("amsDataSystemTestC") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//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", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", ] subsystem_name = "amssystemtestability" } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c1.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c1.h index 7935243c612949e6a82d654695e4558427daffdd..243c40b2e505c9f979bbbecd7103a99a969bd992 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c1.h +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c1.h @@ -22,6 +22,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -40,11 +43,11 @@ public: 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; friend class DataTestDataC1EventSubscriber; diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c2.h b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c2.h index 3fea6b358aeb068a3a860f16fab6a7f80e9c4d6a..186130a4993873b97427fb47e816c5a3a48dc1a1 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c2.h +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/include/ams_st_data_ability_data_c2.h @@ -22,6 +22,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -39,11 +42,11 @@ public: 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; 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..ddf47aa879ba9cbfd5ea6e8eb4e0b71f629a22ff 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 @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_C1_CODE = 230; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -36,6 +37,8 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} bool AmsStDataAbilityDataC1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -90,7 +93,7 @@ void AmsStDataAbilityDataC1::OnStart(const Want &want) PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OnStart"); } -int AmsStDataAbilityDataC1::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStDataAbilityDataC1::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "Insert"); @@ -103,22 +106,22 @@ int AmsStDataAbilityDataC1::Insert(const Uri &uri, const ValuesBucket &value) return DEFAULT_INSERT_RESULT; } -int AmsStDataAbilityDataC1::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataC1::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "Delete"); return DEFAULT_DELETE_RESULT; } -int AmsStDataAbilityDataC1::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataC1::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStDataAbilityDataC1::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStDataAbilityDataC1::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); @@ -127,7 +130,9 @@ std::shared_ptr AmsStDataAbilityDataC1::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_C1_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -135,30 +140,20 @@ std::vector AmsStDataAbilityDataC1::GetFileTypes(const Uri &uri, co { APP_LOGI("AmsStDataAbilityDataC1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } 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, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -168,8 +163,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -183,9 +182,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; + char str[charCnt]; if (!feof(file)) - fgets(str, 5, file); + fgets(str, charCnt, file); result = str; fclose(file); } @@ -196,26 +195,26 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( { if (child->GetOperatorName() == OPERATOR_INSERT) { APP_LOGI("---------------------Insert--------------------"); - AppExecFwk::ValuesBucket bucket; + NativeRdb::ValuesBucket bucket; result = std::to_string(mainAbility->Insert(dataAbilityUri, bucket)); } else if (child->GetOperatorName() == OPERATOR_DELETE) { APP_LOGI("---------------------Delete--------------------"); - AppExecFwk::DataAbilityPredicates predicates; + NativeRdb::DataAbilityPredicates predicates; result = std::to_string(mainAbility->Delete(dataAbilityUri, predicates)); } else if (child->GetOperatorName() == OPERATOR_UPDATE) { APP_LOGI("---------------------Update--------------------"); - AppExecFwk::ValuesBucket bucket; - AppExecFwk::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; result = std::to_string(mainAbility->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { APP_LOGI("---------------------Query--------------------"); std::vector columns = STtools::SerializationStOperatorToVector(*child); - AppExecFwk::DataAbilityPredicates predicates; - std::shared_ptr resultValue = mainAbility->Query(dataAbilityUri, columns, predicates); + NativeRdb::DataAbilityPredicates predicates; + std::shared_ptr resultValue = mainAbility->Query(dataAbilityUri, columns, predicates); + result = "failed"; if (resultValue != nullptr) { - result = resultValue->testInf_; - } else { - result = "failed"; + resultValue->GoToRow(0); + resultValue->GetString(0, result); } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { APP_LOGI("---------------------GetFileTypes--------------------"); @@ -227,18 +226,16 @@ 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); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); + + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } @@ -247,7 +244,7 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( void DataTestDataC1EventSubscriber::TestPost(const std::string funName) { APP_LOGI("DataTestDataC1EventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp index 85edd1abbe650fb5ecac4f5c13e65cb9834c5f7c..a9ba2761636922262ee306aa89ecb54eaba10ec2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_C2_CODE = 240; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -36,6 +37,8 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} bool AmsStDataAbilityDataC2::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -90,29 +93,29 @@ void AmsStDataAbilityDataC2::OnStart(const Want &want) PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "OnStart"); } -int AmsStDataAbilityDataC2::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStDataAbilityDataC2::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "Insert"); return DEFAULT_INSERT_RESULT; } -int AmsStDataAbilityDataC2::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataC2::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "Delete"); return DEFAULT_DELETE_RESULT; } -int AmsStDataAbilityDataC2::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) +int AmsStDataAbilityDataC2::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStDataAbilityDataC2::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStDataAbilityDataC2::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); @@ -121,7 +124,9 @@ std::shared_ptr AmsStDataAbilityDataC2::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_C2_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -129,7 +134,7 @@ std::vector AmsStDataAbilityDataC2::GetFileTypes(const Uri &uri, co { APP_LOGI("AmsStDataAbilityDataC2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_C2_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -149,8 +154,8 @@ int AmsStDataAbilityDataC2::OpenFile(const Uri &uri, const std::string &mode) static void GetResult(std::shared_ptr child, std::shared_ptr helper, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -160,8 +165,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -175,9 +184,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } @@ -186,7 +196,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void DataTestDataC2EventSubscriber::TestPost(const std::string funName) { APP_LOGI("DataTestDataC2EventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp index 009b1c10c2a637fd6a655d187ac75b275e0a42bc..15edde043ef3b74f5245f748ab69bd8ee82c293b 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp @@ -28,14 +28,16 @@ namespace { const std::string currentAbilityName = "KitTestAbilityManagerSecond"; const std::string topAbilityName = "KitTestAbilityManager"; const std::string launchAbilityName = "LauncherAbility"; -const std::string bundleName = "com.ohos.amsst.AppKit"; -const std::string topProcessInfo = "com.ohos.amsst.AppKit"; +const std::string bundleName = "com.ohos.amsst.AppKitAbilityManagerFirst"; +const std::string topProcessInfo = "com.ohos.amsst.AppKitAbilityManagerFirst"; const std::string currentProcessInfo = "com.ohos.amsst.AppKitAbilityManager"; const std::string launchProcessInfo = "com.ix.launcher"; bool isMoveMissionToTop = false; int moveMissionToTopCode = -1; bool isClearUpApplicationData = false; int clearUpApplicationDataCode = -1; +constexpr int numTwo = 2; +constexpr int numThree = 3; } // namespace bool KitTestAbilityManagerSecond::PublishEvent(const std::string &eventName, const int &code, const std::string &data) @@ -110,8 +112,7 @@ void KitTestAbilityManagerSecond::ProcessStateNotEqual( void KitTestAbilityManagerSecond::GetAllStackInfo(MissionStackInfo &missionStackInfo, int stackID) { - StackInfo stackInfo; - stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); + StackInfo stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); for (const auto &stackInfo : stackInfo.missionStackInfos) { if (stackInfo.id == stackID) { missionStackInfo = stackInfo; @@ -206,7 +207,7 @@ void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase4(int code) GetAllStackInfo(missionStackInfo, 1); bool result = false; if (missionStackInfo.missionRecords.size() == 1) { - result = (missionStackInfo.missionRecords[0].abilityRecordInfos.size() == 2); + result = (missionStackInfo.missionRecords[0].abilityRecordInfos.size() == numTwo); } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); } @@ -228,9 +229,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase1"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName) { result = true; } @@ -242,9 +243,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase2"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { result = true; } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); @@ -254,9 +255,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase3"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName && info[0].baseAbility.GetAbilityName() == topAbilityName) { result = true; @@ -270,9 +271,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase1"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName) { result = true; } @@ -284,9 +285,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase2"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { result = true; } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); @@ -296,9 +297,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase3"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); bool result = false; - if (1 == info.size() && 2 == info[0].size) { + if (info.size() == 1 && info[0].size == numTwo) { if (info[0].baseAbility.GetBundleName() == bundleName && info[0].baseAbility.GetAbilityName() == topAbilityName) { result = true; @@ -352,7 +353,7 @@ void KitTestAbilityManagerSecond::OnActive() { APP_LOGI("KitTestAbilityManagerSecond::OnActive"); Ability::OnActive(); - if (true == isMoveMissionToTop) { + if (isMoveMissionToTop == true) { PublishEvent(g_respPageManagerAbilityST, moveMissionToTopCode, "1"); isMoveMissionToTop = false; moveMissionToTopCode = -1; @@ -378,10 +379,10 @@ void KitTestAbilityManagerSecond::OnBackground() { APP_LOGI("KitTestAbilityManagerSecond::OnBackground"); Ability::OnBackground(); - if (true == isMoveMissionToTop) { + if (isMoveMissionToTop == true) { std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); - if (1 == info.size() && 2 == info[0].size) { + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == numTwo) { GetAbilityManager()->MoveMissionToTop(info[0].id); APP_LOGI("GetAbilityManager()->MoveMissionToTop(info[0].id);%{public}d", static_cast(info[0].id)); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ee4f5b143f11998c982c570dd0fe1f3a1ef956d2 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/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") + +config("amsKitSTAbilityManagerConfig") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", + "${aafwk_path}/services/abilitymgr/include", + "${appexecfwk_path}/common/log/include", + "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", + "${appexecfwk_path}/kits/appkit/native/app", + "${appexecfwk_path}/services/bundlemgr/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//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 = \"amsKitSTAbilityManagerFirst\"", + "LOG_DOMAIN = 0xD002200", + ] +} +ohos_shared_library("amsKitSTAbilityManagerFirst") { + sources = [ + "src/kit_test_ability_manager.cpp", + "src/test_utils.cpp", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + configs = [ ":amsKitSTAbilityManagerConfig" ] + deps = [ + "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", + "${aafwk_path}/interfaces/innerkits/base:base", + "${aafwk_path}/interfaces/innerkits/want:want", + "${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", + "//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 = [ + "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/amsKitSTAbilityManagerFirst/config.json b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/config.json new file mode 100644 index 0000000000000000000000000000000000000000..1b39120f4c0247fa3d5fec31d920ca00fe7b99b6 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/config.json @@ -0,0 +1,40 @@ +{ + "app":{ + "bundleName": "com.ohos.amsst.AppKitAbilityManagerFirst", + "vendor": "ix", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package":"com.ohos.KitAbilityManagerFirst.src", + "name":"MainAbility", + "deviceType": [ + "tv", + "car" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [{ + "name": "KitTestAbilityManager", + "icon": "$media:snowflakes", + "label": "Kittest Ability", + "launchType": "singletop", + "orientation": "unspecified", + "type": "page", + "visible": true + }] + } +} \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/kit_test_ability_manager.h b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/kit_test_ability_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..1bc3c529ed1d2eec1a368058024516d4802b4e4b --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/kit_test_ability_manager.h @@ -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. + */ + +#ifndef _KIT_TEST_ABILITY_MANAGER_H_ +#define _KIT_TEST_ABILITY_MANAGER_H_ +#include +#include "ability_loader.h" +#include "running_process_info.h" +#include "ability_manager.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "kit_test_common_info.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using vector_str = std::vector; +using vector_conststr = std::vector; +using vector_func = std::vector>; +using MAP_STR_STR = std::map; +class KitTestManagerEventSubscriber; +class KitTestAbilityManager : public Ability { +public: + void SubscribeEvent(const vector_conststr &eventList); + void AbilityManagerStByCode(int apiIndex, int caseIndex, int code); + void CompareProcessName(std::vector &info, const std::string &expectedName, int code); + void CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code); + void StartAbilitySelf( + const std::string &bundleName, const std::string &abilityNmae, AbilityManagerApi api, int codeIndex, int code); + void GetAllStackInfo(AAFwk::MissionStackInfo &missionStackInfo, int stackID); + + // GetAllRunningProcesses ST kit case + void AbilityManagerGetAllRunningProcessesCase1(int code); + void AbilityManagerGetAllRunningProcessesCase2(int code); + void AbilityManagerGetAllRunningProcessesCase3(int code); + void AbilityManagerGetAllRunningProcessesCase4(int code); + void AbilityManagerGetAllRunningProcessesCase5(int code); + void AbilityManagerGetAllRunningProcessesCase6(int code); + void AbilityManagerGetAllRunningProcessesCase7(int code); + void AbilityManagerGetAllRunningProcessesCase8(int code); + void AbilityManagerGetAllRunningProcessesCase9(int code); + void AbilityManagerGetAllRunningProcessesCase10(int code); + + // GetAllStackInfo ST kit case + void AbilityManagerGetAllStackInfoCase1(int code); + void AbilityManagerGetAllStackInfoCase2(int code); + void AbilityManagerGetAllStackInfoCase3(int code); + void AbilityManagerGetAllStackInfoCase4(int code); + void AbilityManagerGetAllStackInfoCase5(int code); + void AbilityManagerGetAllStackInfoCase6(int code); + void AbilityManagerGetAllStackInfoCase7(int code); + void AbilityManagerGetAllStackInfoCase8(int code); + void AbilityManagerGetAllStackInfoCase9(int code); + + // QueryRecentAbilityMissionInfo ST kit case + void QueryRecentAbilityMissionInfoParam(int numMax, int code, std::size_t size, int flags); + void AbilityManagerQueryRecentAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase3(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase4(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase5(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase6(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase7(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase8(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase9(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase10(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase11(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase12(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase13(int code); + void AbilityManagerQueryRecentAbilityMissionInfoCase14(int code); + + // QueryRunningAbilityMissionInfo ST kit case + void QueryRunningAbilityMissionInfoParam(int numMax, int code, std::size_t size); + void AbilityManagerQueryRunningAbilityMissionInfoCase1(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase2(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase3(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase4(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase5(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase6(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase7(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase8(int code); + void AbilityManagerQueryRunningAbilityMissionInfoCase9(int code); + + // MoveMissionToTop ST kit case + void AbilityManagerMoveMissionToTopCase1(int code); + void AbilityManagerMoveMissionToTopCase2(int code); + + // ClearUpApplicationData ST kit case + void AbilityManagerClearUpApplicationDataCase1(int code); + std::shared_ptr subscriber; + +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: + std::unordered_map mapStKitFunc_{ + {static_cast(AbilityManagerApi::GetAllRunningProcesses), + {{[this](int code) { AbilityManagerGetAllRunningProcessesCase1(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase2(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase3(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase4(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase5(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase6(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase7(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase8(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase9(code); }}, + {[this](int code) { AbilityManagerGetAllRunningProcessesCase10(code); }}}}, + {static_cast(AbilityManagerApi::GetAllStackInfo), + {{[this](int code) { AbilityManagerGetAllStackInfoCase1(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase2(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase3(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase4(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase5(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase6(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase7(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase8(code); }}, + {[this](int code) { AbilityManagerGetAllStackInfoCase9(code); }}}}, + {static_cast(AbilityManagerApi::QueryRecentAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase3(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase4(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase5(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase6(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase7(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase8(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase9(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase10(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase11(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase12(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase13(code); }}, + {[this](int code) { AbilityManagerQueryRecentAbilityMissionInfoCase14(code); }}}}, + {static_cast(AbilityManagerApi::QueryRunningAbilityMissionInfo), + {{[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase1(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase2(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase3(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase4(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase5(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase6(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase7(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase8(code); }}, + {[this](int code) { AbilityManagerQueryRunningAbilityMissionInfoCase9(code); }}}}, + {static_cast(AbilityManagerApi::MoveMissionToTop), + {{[this](int code) { AbilityManagerMoveMissionToTopCase1(code); }}, + {[this](int code) { AbilityManagerMoveMissionToTopCase2(code); }}}}, + {static_cast(AbilityManagerApi::ClearUpApplicationData), + {{[this](int code) { AbilityManagerClearUpApplicationDataCase1(code); }}}}}; +}; + +// KitTestManagerEventSubscriber Class +class KitTestManagerEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + KitTestManagerEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp, KitTestAbilityManager *ability) + : CommonEventSubscriber(sp) + { + mapTestFunc_ = {{"AbilityManagerApi", + [this](int apiIndex, int caseIndex, int code) { AbilityManagerStByCode(apiIndex, caseIndex, code); }}}; + kitTestAbility_ = ability; + } + ~KitTestManagerEventSubscriber() + { + kitTestAbility_ = nullptr; + } + + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; + void AbilityManagerStByCode(int apiIndex, int caseIndex, int code); + void KitTerminateAbility(); + +private: + std::unordered_map> mapTestFunc_; + KitTestAbilityManager *kitTestAbility_; +}; + +} // namespace AppExecFwk +} // namespace OHOS +#endif //_KIT_TEST_ABILITY_MANAGER_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/include/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0af55daf4ded4319a4da63849373fcf9ba3d4b03 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/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/amsKitSTAbilityManagerFirst/src/kit_test_ability_manager.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/kit_test_ability_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..acfa1dcac84ecf129752004481bb407ef6126d98 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/kit_test_ability_manager.cpp @@ -0,0 +1,611 @@ +/* + * 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 "kit_test_ability_manager.h" +#include +#include +#include +#include "app_log_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +namespace { +const std::string bundleName = "com.ohos.amsst.AppKitAbilityManager"; +const std::string abilityName = "KitTestAbilityManagerSecond"; +const std::string currentAbilityName = "KitTestAbilityManager"; +const std::string currentProcessInfo = "com.ohos.amsst.AppKitAbilityManagerFirst"; +const std::string launchAbilityName = "LauncherAbility"; +const std::string launchProcessInfo = "com.ix.launcher"; +bool isMoveMissionToTop = false; +int moveMissionToTopCode = -1; +int isClearUpApplicationData = false; +int numThree = 3; +} // namespace + +void KitTestAbilityManager::SubscribeEvent(const vector_conststr &eventList) +{ + MatchingSkills matchingSkills; + for (const auto &e : eventList) { + matchingSkills.AddEvent(e); + } + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber = std::make_shared(subscribeInfo, this); + CommonEventManager::SubscribeCommonEvent(subscriber); +} + +void KitTestAbilityManager::AbilityManagerStByCode(int apiIndex, int caseIndex, int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerStByCode"); + if (mapStKitFunc_.find(apiIndex) != mapStKitFunc_.end() && + static_cast(mapStKitFunc_[apiIndex].size()) > caseIndex) { + mapStKitFunc_[apiIndex][caseIndex](code); + } else { + APP_LOGI("AbilityManagerStByCode error"); + } +} + +void KitTestAbilityManager::CompareProcessName( + std::vector &info, const std::string &expectedName, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == expectedName) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::CompareProcessState( + std::vector &info, const std::string &processName, AppProcessState expectedState, int code) +{ + bool result = false; + for (auto processInfo : info) { + if (processInfo.processName_ == processName && processInfo.state_ == expectedState) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::StartAbilitySelf( + const std::string &bundleName, const std::string &abilityNmae, AbilityManagerApi api, int codeIndex, int code) +{ + MAP_STR_STR params; + params["apiIndex"] = std::to_string(static_cast(api)); + params["caseIndex"] = std::to_string(codeIndex); + params["code"] = std::to_string(code); + Want want = TestUtils::MakeWant("", abilityNmae, bundleName, params); + StartAbility(want); +} + +void KitTestAbilityManager::GetAllStackInfo(MissionStackInfo &missionStackInfo, int stackID) +{ + StackInfo stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); + for (const auto &missionInfo : stackInfo.missionStackInfos) { + if (missionInfo.id == stackID) { + missionStackInfo = missionInfo; + break; + } + } +} + +// GetAllRunningProcesses ST kit case +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase1"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, currentProcessInfo, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase2"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessName(info, launchProcessInfo, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase3"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + std::shared_ptr processInfo = AbilityContext::GetProcessInfo(); + bool result = false; + for (auto runProcessInfo : info) { + if (runProcessInfo.processName_ == currentProcessInfo && processInfo->GetPid() == runProcessInfo.pid_) { + result = true; + } + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase4"); + std::vector info = AbilityManager::GetInstance().GetAllRunningProcesses(); + CompareProcessState(info, currentProcessInfo, AppProcessState::APP_STATE_FOREGROUND, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase8"); + auto index = 3; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase9"); + auto index = 4; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase10(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllRunningProcessesCase10"); + auto index = 5; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllRunningProcesses, index, code); +} + +// GetAllStackInfo ST kit case +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase1"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + bool result = (missionStackInfo.missionRecords.size() == 1); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase2"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 1); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool result = (abilityInfos[0].mainName.compare(currentAbilityName) == 0); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase3"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + bool result = (missionStackInfo.missionRecords.size() == 1); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase4"); + MissionStackInfo missionStackInfo; + GetAllStackInfo(missionStackInfo, 0); + auto abilityInfos = missionStackInfo.missionRecords[0].abilityRecordInfos; + bool result = (abilityInfos[0].mainName.compare(launchAbilityName) == 0); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase8"); + auto index = 3; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerGetAllStackInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerGetAllStackInfoCase9"); + auto index = 4; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::GetAllStackInfo, index, code); +} + +// QueryRecentAbilityMissionInfo ST kit case +void KitTestAbilityManager::QueryRecentAbilityMissionInfoParam(int numMax, int code, std::size_t size, int flags) +{ + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numMax, flags); + bool result = (info.size() == size); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase1"); + auto num = -1; + auto size = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_IGNORE_UNAVAILABLE); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase2"); + auto num = 3; + auto size = 0; + auto flag = -1; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase3"); + auto num = 3; + auto size = 0; + auto flag = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase4"); + auto num = 3; + auto size = 0; + auto flag = 3; + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase5"); + auto num = 3; + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase6"); + auto num = 3; + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_IGNORE_UNAVAILABLE); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase7"); + std::vector info; + auto num = 3; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(num, RECENT_WITH_EXCLUDED); + bool result = false; + if (info.size() == 1 && info[0].size == 1) { + result = true; + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase8"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase9"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase10(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase10"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRecentAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase11(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase11"); + auto num = std::numeric_limits::min(); + auto size = 0; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase12(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase12"); + auto num = std::numeric_limits::max(); + auto size = 1; + QueryRecentAbilityMissionInfoParam(num, code, size, RECENT_WITH_EXCLUDED); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase13(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase13"); + auto num = 3; + auto size = 0; + auto flag = std::numeric_limits::min(); + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase14(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRecentAbilityMissionInfoCase14"); + auto num = 3; + auto size = 0; + auto flag = std::numeric_limits::max(); + QueryRecentAbilityMissionInfoParam(num, code, size, flag); +} + +// QueryRunningAbilityMissionInfo ST kit case +void KitTestAbilityManager::QueryRunningAbilityMissionInfoParam(int numMax, int code, std::size_t size) +{ + std::vector info; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numMax); + bool result = (info.size() == size); + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase1"); + auto num = -1; + auto flag = 0; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase2"); + auto num = 0; + auto flag = 0; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase3(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase3"); + auto num = 3; + auto flag = 1; + QueryRunningAbilityMissionInfoParam(num, code, flag); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase4(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase4"); + std::vector info; + auto num = 3; + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(num); + bool result = false; + if (info.size() == 1 && info[0].size == 1) { + result = true; + } + TestUtils::PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase5(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase5"); + auto index = 0; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase6(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase6"); + auto index = 1; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase7(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase7"); + auto index = 2; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::QueryRunningAbilityMissionInfo, index, code); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase8(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase8"); + QueryRunningAbilityMissionInfoParam(std::numeric_limits::min(), code, 0); +} + +void KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase9(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerQueryRunningAbilityMissionInfoCase9"); + QueryRunningAbilityMissionInfoParam(std::numeric_limits::max(), code, 1); +} + +// MoveMissionToTop ST kit case +void KitTestAbilityManager::AbilityManagerMoveMissionToTopCase1(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerMoveMissionToTopCase1"); + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::MoveMissionToTop, 0, code); +} + +void KitTestAbilityManager::AbilityManagerMoveMissionToTopCase2(int code) +{ + APP_LOGI("KitTestAbilityManager::AbilityManagerMoveMissionToTopCase2"); + moveMissionToTopCode = code; + isMoveMissionToTop = true; + Want wantEntity; + wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); + StartAbility(wantEntity); +} + +// ClearUpApplicationData ST kit case +void KitTestAbilityManager::AbilityManagerClearUpApplicationDataCase1(int code) +{ + isClearUpApplicationData = true; + StartAbilitySelf(bundleName, abilityName, AbilityManagerApi::ClearUpApplicationData, 0, code); +} + +void KitTestAbilityManager::OnStart(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::onStart"); + Ability::OnStart(want); + SubscribeEvent(g_requPageManagerAbilitySTVector); + std::string eventData = GetAbilityName() + g_abilityStateOnStart; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnStop() +{ + APP_LOGI("KitTestAbilityManager::onStop"); + Ability::OnStop(); + CommonEventManager::UnSubscribeCommonEvent(subscriber); + std::string eventData = GetAbilityName() + g_abilityStateOnStop; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnActive() +{ + APP_LOGI("KitTestAbilityManager::OnActive"); + Ability::OnActive(); + if (isMoveMissionToTop) { + TestUtils::PublishEvent(g_respPageManagerAbilityST, moveMissionToTopCode, "1"); + isMoveMissionToTop = false; + moveMissionToTopCode = -1; + } + std::string eventData = GetAbilityName() + g_abilityStateOnActive; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnInactive() +{ + APP_LOGI("KitTestAbilityManager::OnInactive"); + Ability::OnInactive(); + std::string eventData = GetAbilityName() + g_abilityStateOnInactive; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnBackground() +{ + APP_LOGI("KitTestAbilityManager::OnBackground"); + Ability::OnBackground(); + if (isMoveMissionToTop) { + std::vector info; + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == 1) { + GetAbilityManager()->MoveMissionToTop(info[0].id); + } + } + if (isClearUpApplicationData != false) { + AbilityManager::GetInstance().ClearUpApplicationData(currentProcessInfo); + isClearUpApplicationData = false; + } + std::string eventData = GetAbilityName() + g_abilityStateOnBackground; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnForeground(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::OnForeground"); + Ability::OnForeground(want); + std::string eventData = GetAbilityName() + g_abilityStateOnForeground; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +void KitTestAbilityManager::OnNewWant(const Want &want) +{ + APP_LOGI("KitTestAbilityManager::OnNewWant"); + Ability::OnNewWant(want); + std::string eventData = GetAbilityName() + g_abilityStateOnNewWant; + TestUtils::PublishEvent(g_respPageManagerAbilityST, 0, eventData); +} + +// KitTestManagerEventSubscriber Class +void KitTestManagerEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:event=%{public}s", data.GetWant().GetAction().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:data=%{public}s", data.GetData().c_str()); + APP_LOGI("KitTestEventSubscriber::OnReceiveEvent:code=%{public}d", data.GetCode()); + auto eventName = data.GetWant().GetAction(); + if (g_requPageManagerAbilityST == eventName) { + auto target = data.GetData(); + auto handle = 0; + auto api = 1; + auto code = 2; + auto paramMinSize = 3; + vector_str splitResult = TestUtils::split(target, "_"); + auto keyMap = splitResult.at(handle); + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && + splitResult.size() >= static_cast(paramMinSize)) { + auto apiIndex = atoi(splitResult.at(api).c_str()); + auto caseIndex = atoi(splitResult.at(code).c_str()); + mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); + } else { + if (keyMap == "TerminateAbility") { + KitTerminateAbility(); + } else { + APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); + } + } + } +} + +void KitTestManagerEventSubscriber::AbilityManagerStByCode(int apiIndex, int caseIndex, int code) +{ + if (kitTestAbility_ != nullptr) { + kitTestAbility_->AbilityManagerStByCode(apiIndex, caseIndex, code); + } +} + +void KitTestManagerEventSubscriber::KitTerminateAbility() +{ + if (kitTestAbility_ != nullptr) { + kitTestAbility_->TerminateAbility(); + } +} + +REGISTER_AA(KitTestAbilityManager) +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/test_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f7fa556737647aecddbe3a8190286ad772fbb23 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManagerFirst/src/test_utils.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 "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); + std::vector res = { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; + return res; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of 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/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h index 268205e3660aff79414556e752ffa3cfc2da0173..ec3e1ed23742f4211ec6b87151860cf7d4313888 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class FirstEventSubscriber; class MainAbility : public Ability { public: diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h index d00a9d128cf4f02f8a300db15061ba6809f58b28..385591ba2615eeb89a4438756a7ec7d2b8517d7b 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h @@ -1534,7 +1534,6 @@ public: SecondAbility *secondAbility; std::unordered_map> mapTestFunc_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _AMS_KIT_SYSTEM_TEST_SECOND_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h index cafc175ccd93a09b67aa9625a9d51f199a1d66c8..cf145f0a098b859321a56fff020026d90eafd9bd 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h @@ -254,7 +254,6 @@ public: private: CallbackCount callbackCount_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _Six_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h index 741c48789435a96eabc28bd1306749d03209d116..0af55daf4ded4319a4da63849373fcf9ba3d4b03 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h @@ -34,9 +34,6 @@ public: 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::string ApplicationInfoToString(std::shared_ptr applicationInfo); - static std::string AbilityInfoToString(std::shared_ptr abilityInfo); - static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h index 4ce2399a1f747b1b199b72eeb1933df24f9af30a..f83e7bb013421d718a97b190d761cc8ca85cddad 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h @@ -162,7 +162,6 @@ public: private: std::unordered_map> mapTestFunc_; }; - } // namespace AppExecFwk } // namespace OHOS #endif // _THIRD_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp index 55901e8cc2788b9b506177c3d40c0b835e09abf2..a2a1df81f8b7247901bdde73a7256a4830afb7e4 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 { @@ -238,7 +248,7 @@ void FifthAbility::WantParamsSetParamCase9(int code) TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); } -template +template static void SetArray(const InterfaceID &id, const std::vector &value, sptr &ao) { typename std::vector::size_type size = value.size(); @@ -248,7 +258,7 @@ static void SetArray(const InterfaceID &id, const std::vector &value, sptr +template static void FillArray(IArray *ao, std::vector &array) { auto func = [&](IInterface *object) { array.push_back(T2::Unbox(T3::Query(object))); }; 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..c1054ae2265aa4ba65513975bd8d069a500c923f --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp @@ -18,13 +18,22 @@ #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 { using namespace OHOS::EventFwk; using namespace OHOS::AAFwk; namespace { - const std::string normalString = "kitapp.system.test"; // Special string const std::string specialString = "@#¥#//\\%&*_=+[]^:!~();,.'?3243adsafdf_中文"; @@ -38,402 +47,520 @@ const int cycleCount = 1000; enum class AddFunctionType { Add_String, Add_String_MatchType, Add_PatternMatcher }; } // namespace -#define COUNTFUNCTION(objectName, countFunction, expected, code) \ - int actionCount = objectName.countFunction(); \ - bool result = (actionCount == expected); \ - TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)) - -#define GETFUNCTION(objectName, getFunction, parameter, expected, code) \ - std::string skillAction = objectName.getFunction(parameter); \ - bool result = (skillAction == expected); \ - TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)) - -#define HASFUNCTION(objectName, hasFunction, parameter, expected, code) \ - bool isHas = objectName.hasFunction(parameter); \ - bool result = (isHas == expected); \ - TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)) +#define COUNTFUNCTION(objectName, countFunction, expected, code) \ + do { \ + int actionCount = objectName.countFunction(); \ + bool result = (actionCount == (expected)); \ + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); \ + } while (0); + +#define GETFUNCTION(objectName, getFunction, parameter, expected, code) \ + do { \ + std::string skillAction = objectName.getFunction(parameter); \ + bool result = (skillAction == (expected)); \ + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); \ + } while (0); + +#define HASFUNCTION(objectName, hasFunction, parameter, expected, code) \ + do { \ + bool isHas = objectName.hasFunction(parameter); \ + bool result = (isHas == (expected)); \ + TestUtils::PublishEvent(g_respPageFourthAbilityST, code, std::to_string(result)); \ + } while (0); // Add Path and Type Define Function -#define ADDFUNCTION(objeceName, addFunction, stringParameter, addFunctionType) \ - if (AddFunctionType::Add_String == addFunctionType) { \ - objeceName.addFunction(stringParameter); \ - } else if (AddFunctionType::Add_String_MatchType == addFunctionType) { \ - skill.addFunction(stringParameter, MatchType::PREFIX); \ - } else { \ - PatternsMatcher pm(stringParameter, MatchType::PREFIX); \ - skill.addFunction(pm); \ - } +#define ADDFUNCTION(objeceName, addFunction, stringParameter, addFunctionType) \ + do { \ + if (AddFunctionType::Add_String == (addFunctionType)) { \ + objeceName.addFunction((stringParameter)); \ + } else if (AddFunctionType::Add_String_MatchType == (addFunctionType)) { \ + skill.addFunction((stringParameter), MatchType::PREFIX); \ + } else { \ + PatternsMatcher pm((stringParameter), MatchType::PREFIX); \ + skill.addFunction(pm); \ + } \ + } while (0); #define REMOVEFUNCTION(objeceName, removeFunction, stringParameter, addFunctionType) \ - if (AddFunctionType::Add_String == addFunctionType) { \ - objeceName.removeFunction(stringParameter); \ - } else if (AddFunctionType::Add_String_MatchType == addFunctionType) { \ - skill.removeFunction(stringParameter, MatchType::PREFIX); \ - } else { \ - PatternsMatcher pm(stringParameter, MatchType::PREFIX); \ - skill.removeFunction(pm); \ - } + do { \ + if (AddFunctionType::Add_String == (addFunctionType)) { \ + objeceName.removeFunction((stringParameter)); \ + } else if (AddFunctionType::Add_String_MatchType == (addFunctionType)) { \ + skill.removeFunction((stringParameter), MatchType::PREFIX); \ + } else { \ + PatternsMatcher pm((stringParameter), MatchType::PREFIX); \ + skill.removeFunction(pm); \ + } \ + } while (0); // Add and Count ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) #define SKILLS_ADD_AND_COUNT_CASE1(addFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(normalString); \ - COUNTFUNCTION(skill, countFunction, 1, code) + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); #define SKILLS_ADD_AND_COUNT_CASE2(countFunction, code) \ - Skills skill; \ - COUNTFUNCTION(skill, countFunction, 0, code) + do { \ + Skills skill; \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); #define SKILLS_ADD_AND_COUNT_CASE3(addFunction, countFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - COUNTFUNCTION(skill, countFunction, 1, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); // Add and Get ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) #define SKILLS_ADD_AND_GET_CASE1(addFunction, getFunction, code) \ - Skills skill; \ - skill.addFunction(normalString); \ - GETFUNCTION(skill, getFunction, 0, normalString, code) + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + GETFUNCTION(skill, getFunction, 0, normalString, code); \ + } while (0); #define SKILLS_ADD_AND_GET_CASE2(addFunction, getFunction, code) \ - Skills skill; \ - skill.addFunction(normalString); \ - GETFUNCTION(skill, getFunction, 10, std::string(), code) - -#define SKILLS_ADD_AND_GET_CASE3(addFunction, getFunction, code) \ - Skills skill; \ - skill.addFunction(normalString); \ - GETFUNCTION(skill, getFunction, -10, std::string(), code) - -#define SKILLS_ADD_AND_GET_CASE4(getFunction, code) \ - Skills skill; \ - GETFUNCTION(skill, getFunction, 0, std::string(), code) + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + GETFUNCTION(skill, getFunction, 10, std::string(), code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE3(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + GETFUNCTION(skill, getFunction, -10, std::string(), code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE4(getFunction, code) \ + do { \ + Skills skill; \ + GETFUNCTION(skill, getFunction, 0, std::string(), code) \ + } while (0); #define SKILLS_ADD_AND_GET_CASE5(addFunction, getFunction, code) \ - Skills skill; \ - skill.addFunction(specialString); \ - GETFUNCTION(skill, getFunction, 0, specialString, code) + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + GETFUNCTION(skill, getFunction, 0, specialString, code); \ + } while (0); #define SKILLS_ADD_AND_GET_CASE6(addFunction, getFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - GETFUNCTION(skill, getFunction, 0, normalString, code) - -#define SKILLS_ADD_AND_GET_CASE7(addFunction, getFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - GETFUNCTION(skill, getFunction, 150, std::string(), code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + GETFUNCTION(skill, getFunction, 0, normalString, code); \ + } while (0); + +#define SKILLS_ADD_AND_GET_CASE7(addFunction, getFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + GETFUNCTION(skill, getFunction, 150, std::string(), code) \ + } while (0); // Add and Has ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) -#define SKILLS_ADD_AND_HAS_CASE1(addFunction, hasFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - HASFUNCTION(skill, hasFunction, normalString, true, code) - -#define SKILLS_ADD_AND_HAS_CASE2(hasFunction, code) \ - Skills skill; \ - HASFUNCTION(skill, hasFunction, normalString, false, code) - -#define SKILLS_ADD_AND_HAS_CASE3(addFunction, hasFunction, code) \ - Skills skill; \ - skill.addFunction(specialString); \ - HASFUNCTION(skill, hasFunction, specialString, true, code) +#define SKILLS_ADD_AND_HAS_CASE1(addFunction, hasFunction, code) \ + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + HASFUNCTION(skill, hasFunction, normalString, true, code); \ + } while (0); + +#define SKILLS_ADD_AND_HAS_CASE2(hasFunction, code) \ + do { \ + Skills skill; \ + HASFUNCTION(skill, hasFunction, normalString, false, code); \ + } while (0); + +#define SKILLS_ADD_AND_HAS_CASE3(addFunction, hasFunction, code) \ + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + HASFUNCTION(skill, hasFunction, specialString, true, code); \ + } while (0); // Add,Remove,Count and Has ST kit Case(Action,Entity,Authority,Scheme,SchemeSpecificPart) #define SKILLS_ADD_AND_REMOVE_CASE1(addFunction, removeFunction, hasFunction, code) \ - Skills skill; \ - skill.addFunction(specialString); \ - skill.removeFunction(specialString); \ - HASFUNCTION(skill, hasFunction, specialString, false, code) + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.removeFunction(specialString); \ + HASFUNCTION(skill, hasFunction, specialString, false, code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE2(addFunction, removeFunction, getFunction, code) \ - Skills skill; \ - skill.addFunction(specialString); \ - skill.removeFunction(specialString); \ - GETFUNCTION(skill, getFunction, 0, std::string(), code) + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.removeFunction(specialString); \ + GETFUNCTION(skill, getFunction, 0, std::string(), code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE3(addFunction, removeFunction, hasFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - skill.removeFunction(normalString); \ - HASFUNCTION(skill, hasFunction, normalString, false, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(normalString); \ + HASFUNCTION(skill, hasFunction, normalString, false, code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE4(addFunction, removeFunction, hasFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - skill.removeFunction(specialString); \ - HASFUNCTION(skill, hasFunction, normalString, true, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(specialString); \ + HASFUNCTION(skill, hasFunction, normalString, true, code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE5(addFunction, removeFunction, getFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - skill.removeFunction(normalString); \ - GETFUNCTION(skill, getFunction, 150, std::string(), code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(normalString); \ + GETFUNCTION(skill, getFunction, 150, std::string(), code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE6(addFunction, removeFunction, getFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - skill.removeFunction(specialString); \ - GETFUNCTION(skill, getFunction, 0, normalString, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(specialString); \ + GETFUNCTION(skill, getFunction, 0, normalString, code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE7(addFunction, removeFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(specialString); \ - skill.removeFunction(specialString); \ - COUNTFUNCTION(skill, countFunction, 0, code) + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.removeFunction(specialString); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE8(addFunction, removeFunction, countFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - skill.removeFunction(normalString); \ - COUNTFUNCTION(skill, countFunction, 0, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(normalString); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); #define SKILLS_ADD_AND_REMOVE_CASE9(addFunction, removeFunction, countFunction, code) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - skill.addFunction(normalString); \ - } \ - skill.removeFunction(specialString); \ - COUNTFUNCTION(skill, countFunction, 1, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + skill.addFunction(normalString); \ + } \ + skill.removeFunction(specialString); \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); // Add and Count ST kit Case(Path,Type) #define SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE1(addFunction, countFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - COUNTFUNCTION(skill, countFunction, 1, code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE2(countFunction, code) \ - Skills skill; \ - COUNTFUNCTION(skill, countFunction, 0, code) + do { \ + Skills skill; \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_COUNT_CASE3(addFunction, countFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - COUNTFUNCTION(skill, countFunction, 1, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); // Add and Get ST kit Case(Path,Type) #define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE1(addFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - GETFUNCTION(skill, getFunction, 0, normalPathAndType, code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 0, normalPathAndType, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE2(addFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - GETFUNCTION(skill, getFunction, 10, std::string(), code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 10, std::string(), code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE3(addFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - GETFUNCTION(skill, getFunction, -10, std::string(), code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + GETFUNCTION(skill, getFunction, -10, std::string(), code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE4(getFunction, code) \ - Skills skill; \ - GETFUNCTION(skill, getFunction, 0, std::string(), code) + do { \ + Skills skill; \ + GETFUNCTION(skill, getFunction, 0, std::string(), code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE5(addFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, specialString, addFunctionType) \ - GETFUNCTION(skill, getFunction, 0, specialString, code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)) \ + GETFUNCTION(skill, getFunction, 0, specialString, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE6(addFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - GETFUNCTION(skill, getFunction, 0, normalPathAndType, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + GETFUNCTION(skill, getFunction, 0, normalPathAndType, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_GET_CASE7(addFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - GETFUNCTION(skill, getFunction, 150, std::string(), code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + GETFUNCTION(skill, getFunction, 150, std::string(), code); \ + } while (0); // Add and Has ST kit Case(Path,Type) #define SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE1(addFunction, hasFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - HASFUNCTION(skill, hasFunction, normalPathAndType, true, code) - -#define SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE2(hasFunction, code) \ - Skills skill; \ - HASFUNCTION(skill, hasFunction, normalPathAndType, false, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + HASFUNCTION(skill, hasFunction, normalPathAndType, true, code); \ + } while (0); + +#define SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE2(hasFunction, code) \ + do { \ + Skills skill; \ + HASFUNCTION(skill, hasFunction, normalPathAndType, false, code) \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_HAS_CASE3(addFunction, hasFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, specialString, addFunctionType) \ - HASFUNCTION(skill, hasFunction, specialString, true, code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)) \ + HASFUNCTION(skill, hasFunction, specialString, true, code); \ + } while (0); // Add,Remove,Count and Has ST kit Case(Path,Type) #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE1(addFunction, removeFunction, hasFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, specialString, addFunctionType) \ - REMOVEFUNCTION(skill, removeFunction, specialString, addFunctionType) \ - HASFUNCTION(skill, hasFunction, specialString, false, code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)); \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + HASFUNCTION(skill, hasFunction, specialString, false, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE2(addFunction, removeFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, specialString, addFunctionType) \ - REMOVEFUNCTION(skill, removeFunction, specialString, addFunctionType) \ - GETFUNCTION(skill, getFunction, 0, std::string(), code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)); \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 0, std::string(), code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE3(addFunction, removeFunction, hasFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - REMOVEFUNCTION(skill, removeFunction, normalPathAndType, addFunctionType) \ - HASFUNCTION(skill, hasFunction, normalPathAndType, false, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, normalPathAndType, (addFunctionType)); \ + HASFUNCTION(skill, hasFunction, normalPathAndType, false, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE4(addFunction, removeFunction, hasFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - REMOVEFUNCTION(skill, removeFunction, specialString, addFunctionType) \ - HASFUNCTION(skill, hasFunction, normalPathAndType, true, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + HASFUNCTION(skill, hasFunction, normalPathAndType, true, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE5(addFunction, removeFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - REMOVEFUNCTION(skill, removeFunction, normalPathAndType, addFunctionType) \ - GETFUNCTION(skill, getFunction, 150, std::string(), code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, normalPathAndType, (addFunctionType)) ; \ + GETFUNCTION(skill, getFunction, 150, std::string(), code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE6(addFunction, removeFunction, getFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - REMOVEFUNCTION(skill, removeFunction, specialString, addFunctionType) \ - GETFUNCTION(skill, getFunction, 0, normalPathAndType, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + GETFUNCTION(skill, getFunction, 0, normalPathAndType, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE7(addFunction, removeFunction, countFunction, code, addFunctionType) \ - Skills skill; \ - ADDFUNCTION(skill, addFunction, specialString, addFunctionType) \ - REMOVEFUNCTION(skill, removeFunction, specialString, addFunctionType) \ - COUNTFUNCTION(skill, countFunction, 0, code) + do { \ + Skills skill; \ + ADDFUNCTION(skill, addFunction, specialString, (addFunctionType)); \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE8(addFunction, removeFunction, countFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - REMOVEFUNCTION(skill, removeFunction, normalPathAndType, addFunctionType) \ - COUNTFUNCTION(skill, countFunction, 0, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)); \ + } \ + REMOVEFUNCTION(skill, removeFunction, normalPathAndType, (addFunctionType)); \ + COUNTFUNCTION(skill, countFunction, 0, code) \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE9(addFunction, removeFunction, countFunction, code, addFunctionType) \ - Skills skill; \ - for (int index = 0; index < cycleCount; index++) { \ - ADDFUNCTION(skill, addFunction, normalPathAndType, addFunctionType) \ - } \ - REMOVEFUNCTION(skill, removeFunction, specialString, addFunctionType) \ - COUNTFUNCTION(skill, countFunction, 1, code) + do { \ + Skills skill; \ + for (int index = 0; index < cycleCount; index++) { \ + ADDFUNCTION(skill, addFunction, normalPathAndType, (addFunctionType)) \ + } \ + REMOVEFUNCTION(skill, removeFunction, specialString, (addFunctionType)) \ + COUNTFUNCTION(skill, countFunction, 1, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE10(addFunction, removeFunction, hasFunction, code) \ - Skills skill; \ - skill.addFunction(specialString); \ - skill.addFunction(specialString, MatchType::PREFIX); \ - skill.removeFunction(specialString); \ - HASFUNCTION(skill, hasFunction, specialString, true, code) + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.addFunction(specialString, MatchType::PREFIX); \ + skill.removeFunction(specialString); \ + HASFUNCTION(skill, hasFunction, specialString, true, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE11(addFunction, removeFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(specialString, MatchType::DEFAULT); \ - skill.addFunction(specialString, MatchType::PREFIX); \ - skill.addFunction(specialString, MatchType::GLOBAL); \ - skill.removeFunction(specialString); \ - COUNTFUNCTION(skill, countFunction, 2, code) + do { \ + Skills skill; \ + skill.addFunction(specialString, MatchType::DEFAULT); \ + skill.addFunction(specialString, MatchType::PREFIX); \ + skill.addFunction(specialString, MatchType::GLOBAL); \ + skill.removeFunction(specialString); \ + COUNTFUNCTION(skill, countFunction, 2, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE12(addFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(specialString); \ - skill.addFunction(specialString, MatchType::DEFAULT); \ - skill.addFunction(specialString, MatchType::PREFIX); \ - skill.addFunction(specialString, MatchType::GLOBAL); \ - COUNTFUNCTION(skill, countFunction, 3, code) + do { \ + Skills skill; \ + skill.addFunction(specialString); \ + skill.addFunction(specialString, MatchType::DEFAULT); \ + skill.addFunction(specialString, MatchType::PREFIX); \ + skill.addFunction(specialString, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 3, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE13(addFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(skillspecialTypeStr1); \ - skill.addFunction(skillspecialTypeStr1, MatchType::DEFAULT); \ - skill.addFunction(skillspecialTypeStr1, MatchType::PREFIX); \ - skill.addFunction(skillspecialTypeStr1, MatchType::GLOBAL); \ - COUNTFUNCTION(skill, countFunction, 0, code) + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr1); \ + skill.addFunction(skillspecialTypeStr1, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr1, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr1, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 0, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE14(addFunction, hasFunction, code) \ - Skills skill; \ - skill.addFunction(skillspecialTypeStr1); \ - skill.addFunction(skillspecialTypeStr1, MatchType::DEFAULT); \ - skill.addFunction(skillspecialTypeStr1, MatchType::PREFIX); \ - skill.addFunction(skillspecialTypeStr1, MatchType::GLOBAL); \ - HASFUNCTION(skill, hasFunction, skillspecialTypeStr1, false, code) + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr1); \ + skill.addFunction(skillspecialTypeStr1, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr1, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr1, MatchType::GLOBAL); \ + HASFUNCTION(skill, hasFunction, skillspecialTypeStr1, false, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE15(addFunction, hasFunction, code) \ - Skills skill; \ - skill.addFunction(skillspecialTypeStr2); \ - skill.addFunction(skillspecialTypeStr2, MatchType::DEFAULT); \ - skill.addFunction(skillspecialTypeStr2, MatchType::PREFIX); \ - skill.addFunction(skillspecialTypeStr2, MatchType::GLOBAL); \ - HASFUNCTION(skill, hasFunction, skillspecialTypeStr1, true, code) + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr2); \ + skill.addFunction(skillspecialTypeStr2, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr2, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr2, MatchType::GLOBAL); \ + HASFUNCTION(skill, hasFunction, skillspecialTypeStr1, true, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE16(addFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(skillspecialTypeStr2); \ - skill.addFunction(skillspecialTypeStr2, MatchType::DEFAULT); \ - skill.addFunction(skillspecialTypeStr2, MatchType::PREFIX); \ - skill.addFunction(skillspecialTypeStr2, MatchType::GLOBAL); \ - COUNTFUNCTION(skill, countFunction, 3, code) + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr2); \ + skill.addFunction(skillspecialTypeStr2, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr2, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr2, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 3, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE17(addFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(skillspecialTypeStr3); \ - skill.addFunction(skillspecialTypeStr3, MatchType::DEFAULT); \ - skill.addFunction(skillspecialTypeStr3, MatchType::PREFIX); \ - skill.addFunction(skillspecialTypeStr3, MatchType::GLOBAL); \ - COUNTFUNCTION(skill, countFunction, 3, code) + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr3); \ + skill.addFunction(skillspecialTypeStr3, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr3, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr3, MatchType::GLOBAL); \ + COUNTFUNCTION(skill, countFunction, 3, code); \ + } while (0); #define SKILLS_ADDFUNCTIONTYPE_AND_REMOVE_CASE18(addFunction, hasFunction, code) \ - Skills skill; \ - skill.addFunction(skillspecialTypeStr3); \ - skill.addFunction(skillspecialTypeStr3, MatchType::DEFAULT); \ - skill.addFunction(skillspecialTypeStr3, MatchType::PREFIX); \ - skill.addFunction(skillspecialTypeStr3, MatchType::GLOBAL); \ - HASFUNCTION(skill, hasFunction, skillspecialTypeStr3, true, code) + do { \ + Skills skill; \ + skill.addFunction(skillspecialTypeStr3); \ + skill.addFunction(skillspecialTypeStr3, MatchType::DEFAULT); \ + skill.addFunction(skillspecialTypeStr3, MatchType::PREFIX); \ + skill.addFunction(skillspecialTypeStr3, MatchType::GLOBAL); \ + HASFUNCTION(skill, hasFunction, skillspecialTypeStr3, true, code); \ + } while (0); // Skills Add ST Case #define SKILLS_ADD_CASE1(addFunction, countFunction, code) \ - Skills skill; \ - skill.addFunction(normalString); \ - skill.addFunction(specialString); \ - skill.addFunction(specialString); \ - skill.addFunction(normalPathAndType); \ - skill.addFunction("Ams_Kit_ST_Case"); \ - COUNTFUNCTION(skill, countFunction, 4, code) + do { \ + Skills skill; \ + skill.addFunction(normalString); \ + skill.addFunction(specialString); \ + skill.addFunction(specialString); \ + skill.addFunction(normalPathAndType); \ + skill.addFunction("Ams_Kit_ST_Case"); \ + COUNTFUNCTION(skill, countFunction, 4, code); \ + } while (0); void FourthAbility::SubscribeEvent(const vector_conststr &eventList) { @@ -2376,4 +2503,4 @@ void KitTestFourthEventSubscriber::KitTerminateAbility() REGISTER_AA(FourthAbility) } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp index 121c03c7696bb58beb078f251156ce2ff66f2ad4..484d0c62b7a7468b0c416d5aa328f957d8e71495 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp @@ -21,10 +21,8 @@ namespace OHOS { namespace AppExecFwk { - using namespace OHOS::EventFwk; using namespace OHOS::AAFwk; - namespace { const std::string bundleName = "com.ohos.amsst.AppKitAbilityManager"; const std::string abilityName = "KitTestAbilityManagerSecond"; @@ -35,6 +33,7 @@ const std::string launchProcessInfo = "com.ix.launcher"; bool isMoveMissionToTop = false; int moveMissionToTopCode = -1; int isClearUpApplicationData = false; +int numThree = 3; } // namespace void KitTestAbilityManager::SubscribeEvent(const vector_conststr &eventList) @@ -534,8 +533,8 @@ void KitTestAbilityManager::OnBackground() Ability::OnBackground(); if (isMoveMissionToTop) { std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); - if (1 == info.size() && 1 == info[0].size) { + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + if (info.size() == 1 && info[0].size == 1) { GetAbilityManager()->MoveMissionToTop(info[0].id); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp index 8847d2be14333c1638ae5c070a5f2d6ccc844bc9..cfd54c7116f9ef39a5078997851729a45e407011 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp @@ -162,7 +162,6 @@ void MainAbility::GetAbilityPackageCase1(int code) // get want from empty Want void MainAbility::GetWantCase1(int code) { - Want want; auto getWant = Ability::GetWant(); bool result = getWant == nullptr; TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); @@ -172,7 +171,6 @@ void MainAbility::GetWantCase1(int code) void MainAbility::GetWantCase2(int code) { std::string action = "action"; - Want want; Want setWant; setWant.SetAction(action); Ability::SetWant(setWant); @@ -184,7 +182,6 @@ void MainAbility::GetWantCase2(int code) void MainAbility::GetWantCase3(int code) { std::string action = "action"; - Want want; bool result = true; std::string tmpAction; for (int i = 0; i < pressureTimes; i++) { @@ -217,7 +214,6 @@ void MainAbility::DumpCase1(int code) void MainAbility::SetWantCase1(int code) { std::string empty; - Want want; Want setWant; Ability::SetWant(setWant); bool result = Ability::GetWant()->GetAction() == empty; @@ -228,7 +224,6 @@ void MainAbility::SetWantCase1(int code) void MainAbility::SetWantCase2(int code) { std::string action = "action"; - Want want; std::string tmpAction; for (int i = 0; i < pressureTimes; i++) { Want setWant; 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..2f2a3710e19377507e3536aef93df5de7fcfe9d2 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp @@ -19,14 +19,34 @@ #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 { using namespace AAFwk; using namespace OHOS::EventFwk; - +namespace { constexpr size_t ARRAY_SIZE = 10000; constexpr int LARGE_STR_LEN = 65534; +constexpr int SMALL_INT = 5; +constexpr unsigned setValue = 128; +constexpr unsigned addValue = 64; +constexpr unsigned removeValue = 128; +constexpr int even = 2; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +} bool SecondAbility::CompareWantNoParams(const Want &source, const Want &target) { @@ -141,8 +161,8 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (caseInfo.size() < static_cast(paramMinSize)) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -1139,7 +1159,7 @@ void SecondAbility::WantMarshallingCase19(int code) { Want want; std::string key = "key"; - long value = 99l; + long value = 99L; want.SetParam(key, value); Parcel parcel; bool result = want.Marshalling(parcel); @@ -1157,7 +1177,7 @@ void SecondAbility::WantMarshallingCase20(int code) { Want want; std::string key = "key"; - std::vector value = {99l, 999l, 9999l, 99999l}; + std::vector value = {99L, 999L, 9999L, 99999L}; want.SetParam(key, value); Parcel parcel; bool result = want.Marshalling(parcel); @@ -1274,7 +1294,7 @@ void SecondAbility::WantRemoveEntityCase2(int code) void SecondAbility::WantRemoveEntityCase3(int code) { Want want; - std::vector entities{"entity1", "entity2", "entity3"}; + std::vector entities {"entity1", "entity2", "entity3"}; bool result = true; for (const auto &entity : entities) { want.AddEntity(entity); @@ -1926,7 +1946,7 @@ void SecondAbility::WantParseUriCase23(int code) bool result = (want != nullptr); if (want != nullptr) { auto parsedValue = want->GetStringArrayParam(key); - result = result && (parsedValue == (std::vector{"aa", "bb", "cc"})); + result = result && (parsedValue == (std::vector {"aa", "bb", "cc"})); delete want; } TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); @@ -2264,8 +2284,6 @@ void SecondAbility::WantSetFlagsCase6(int code) // set and add flags void SecondAbility::WantSetFlagsCase7(int code) { - unsigned setValue = 2 ^ 7; - unsigned addValue = 2 ^ 6; Want want; want.SetFlags(setValue); want.AddFlags(addValue); @@ -2276,8 +2294,6 @@ void SecondAbility::WantSetFlagsCase7(int code) // add and set flags void SecondAbility::WantSetFlagsCase8(int code) { - unsigned setValue = 2 ^ 7; - unsigned addValue = 2 ^ 6; Want want; want.AddFlags(addValue); want.SetFlags(setValue); @@ -2288,8 +2304,6 @@ void SecondAbility::WantSetFlagsCase8(int code) // add one flags and remove another flags void SecondAbility::WantSetFlagsCase9(int code) { - unsigned removeValue = 128; - unsigned addValue = 64; Want want; want.AddFlags(addValue); want.RemoveFlags(removeValue); @@ -2665,7 +2679,7 @@ void SecondAbility::WantToUriCase11(int code) void SecondAbility::WantToUriCase12(int code) { std::string key = std::to_string(Long::SIGNATURE) + ".#Want;key=\"\\b\\\";end"; - long value = 9999l; + long value = 9999L; Want want; want.SetParam(key, value); Want *newWant = nullptr; @@ -2984,7 +2998,7 @@ void SecondAbility::WantGetByteParamCase3(int code) Want want; bool result = true; for (int i = 0; i < pressureTimes; i++) { - value = i % 128; + value = i % setValue; want.SetParam(key, value); result = result && want.GetByteParam(key, defaultValue) == value; } @@ -3019,7 +3033,7 @@ void SecondAbility::WantGetByteArrayParamCase3(int code) Want want; bool result = true; for (int i = 0; i < pressureTimes; i++) { - value[0] = i % 128; + value[0] = i % setValue; want.SetParam(key, value); result = result && want.GetByteArrayParam(key) == value; } @@ -3057,7 +3071,7 @@ void SecondAbility::WantGetBoolParamCase3(int code) Want want; bool result = true; for (int i = 0; i < pressureTimes; i++) { - value = i % 2 == 0; + value = i % even == 0; want.SetParam(key, value); result = result && want.GetBoolParam(key, defaultValue) == value; } @@ -3405,8 +3419,8 @@ void SecondAbility::WantGetLongParamCase1(int code) void SecondAbility::WantGetLongParamCase2(int code) { std::string key = "key"; - long value = 10l; - long defaultValue = 7l; + long value = 10L; + long defaultValue = 7L; Want want; want.SetParam(key, value); bool result = want.GetLongParam(key, defaultValue) == value; @@ -3418,7 +3432,7 @@ void SecondAbility::WantGetLongParamCase3(int code) { std::string key = "key"; long value; - long defaultValue = 7l; + long defaultValue = 7L; Want want; bool result = true; for (int i = 0; i < pressureTimes; i++) { @@ -3442,7 +3456,7 @@ void SecondAbility::WantGetLongArrayParamCase1(int code) void SecondAbility::WantGetLongArrayParamCase2(int code) { std::string key = "key"; - std::vector value = {1l, 12l, 127l}; + std::vector value = {1L, 12L, 127L}; Want want; want.SetParam(key, value); bool result = want.GetLongArrayParam(key) == value; @@ -3453,7 +3467,7 @@ void SecondAbility::WantGetLongArrayParamCase2(int code) void SecondAbility::WantGetLongArrayParamCase3(int code) { std::string key = "key"; - std::vector value = {1l, 12l, 127l}; + std::vector value = {1L, 12L, 127L}; Want want; bool result = true; for (int i = 0; i < pressureTimes; i++) { @@ -3478,7 +3492,7 @@ void SecondAbility::WantGetShortParamCase1(int code) void SecondAbility::WantGetShortParamCase2(int code) { std::string key = "key"; - short value = 10l; + short value = 10; short defaultValue = 7; Want want; want.SetParam(key, value); @@ -4097,7 +4111,7 @@ void SecondAbility::WantSetParamIntArrayCase1(int code) void SecondAbility::WantSetParamIntArrayCase2(int code) { std::string key = "key"; - std::vector value(ARRAY_SIZE, 5); + std::vector value(ARRAY_SIZE, SMALL_INT); Want want; want.SetParam(key, value); bool result = want.GetIntArrayParam(key) == value; @@ -5129,24 +5143,24 @@ void SecondAbility::WantOperationEqualsCase2(int code) OperationBuilder opBuilder; std::vector vec = {"entities1", "entities2"}; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .WithEntities(vec) - .WithFlags(1) - .WithUri(Uri("uri")) - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); Want wantOne; wantOne.SetOperation(*operation); OperationBuilder opBuilderTwo; auto operationTwo = opBuilderTwo.WithAbilityName("abilityName2") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .WithEntities(vec) - .WithFlags(1) - .WithUri(Uri("uri")) - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); Want wantTwo; wantTwo.SetOperation(*operationTwo); bool result = !wantOne.OperationEquals(wantTwo); @@ -5158,18 +5172,18 @@ void SecondAbility::WantOperationEqualsCase3(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantOne; wantOne.SetOperation(*operation); OperationBuilder opBuilderTwo; auto operationTwo = opBuilderTwo.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantTwo; wantTwo.SetOperation(*operationTwo); bool result = wantOne.OperationEquals(wantTwo); @@ -5181,10 +5195,10 @@ void SecondAbility::WantOperationEqualsCase4(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName" + std::to_string(pressureTimes - 1)) - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantOne; wantOne.SetOperation(*operation); Want wantTwo; @@ -5193,10 +5207,10 @@ void SecondAbility::WantOperationEqualsCase4(int code) bool result = true; for (int i = 0; i < pressureTimes; i++) { operationTwo = opBuilderTwo.WithAbilityName("abilityName" + std::to_string(i)) - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); wantTwo.SetOperation(*operationTwo); if (i == pressureTimes - 1) { result = result && wantOne.OperationEquals(wantTwo); @@ -5225,10 +5239,10 @@ void SecondAbility::WantCloneOperationCase2(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want want; want.SetOperation(*operation); Want *wantClone = want.CloneOperation(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp index 4b61a8c75357304e0ce910ff4aea54f85d97d546..e47f52510313182dac419e7c7eb224ab34391b03 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp @@ -26,6 +26,8 @@ using namespace OHOS::EventFwk; namespace { const int cycleCount = 1000; +const int paramCnt = 3; +const int caseIndx = 2; } // namespace #define APPREGISTERABILITYLIFECYCALLBACK(onAbilityFunctionName, getAbilityCountFunction, expected, code) \ @@ -466,9 +468,9 @@ void KitTestSixEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); vector_str splitResult = TestUtils::split(target, "_"); auto keyMap = splitResult.at(0); - if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && splitResult.size() >= 3) { + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && splitResult.size() >= paramCnt) { auto apiIndex = atoi(splitResult.at(1).c_str()); - auto caseIndex = atoi(splitResult.at(2).c_str()); + auto caseIndex = atoi(splitResult.at(caseIndx).c_str()); mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); } else { if (keyMap == "TerminateAbility") { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp index b9d744c1e6d8458333507c763ca7ce47487e382d..1f7fa556737647aecddbe3a8190286ad772fbb23 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp @@ -45,85 +45,12 @@ Want TestUtils::MakeWant( return want; } -std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) -{ - std::stringstream sstream; - sstream << "name:" << applicationInfo->name << ","; - sstream << "bundleName:" << applicationInfo->bundleName << ","; - sstream << "description:" << applicationInfo->description << ","; - sstream << "iconPath:" << applicationInfo->iconPath << ","; - sstream << "label:" << applicationInfo->label << ","; - sstream << "deviceId:" << applicationInfo->deviceId << ","; - sstream << "signatureKey:" << applicationInfo->signatureKey << ","; - sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; - sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; - sstream << "supportedModes:" << applicationInfo->supportedModes << ","; - sstream << "process:" << applicationInfo->process << ","; - std::string permissions = - std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - std::string moduleSourceDirs = std::accumulate( - applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); - sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; - sstream << "entryDir:" << applicationInfo->entryDir << ","; - sstream << "codePath:" << applicationInfo->codePath << ","; - sstream << "dataDir:" << applicationInfo->dataDir << ","; - sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; - sstream << "cacheDir:" << applicationInfo->cacheDir; - return sstream.str(); -} - -std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) -{ - std::stringstream sstream; - sstream << "name:" << abilityInfo->name << ","; - sstream << "label:" << abilityInfo->label << ","; - sstream << "description:" << abilityInfo->description << ","; - sstream << "iconPath:" << abilityInfo->iconPath << ","; - sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; - sstream << "kind:" << abilityInfo->kind << ","; - auto type = static_cast::type>(abilityInfo->type); - sstream << "type:" << type << ","; - auto orientation = - static_cast::type>(abilityInfo->orientation); - sstream << "orientation:" << orientation << ","; - auto launchMode = static_cast::type>(abilityInfo->launchMode); - sstream << "launchMode:" << launchMode << ","; - std::string permissions = - std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - sstream << "process:" << abilityInfo->process << ","; - std::string deviceTypes = - std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); - sstream << "deviceTypes:" << deviceTypes << ","; - std::string deviceCapabilities = std::accumulate( - abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); - sstream << "deviceCapabilities:" << deviceCapabilities << ","; - sstream << "uri:" << abilityInfo->uri << ","; - sstream << "package:" << abilityInfo->package << ","; - sstream << "bundleName:" << abilityInfo->bundleName << ","; - sstream << "moduleName:" << abilityInfo->moduleName << ","; - sstream << "applicationName:" << abilityInfo->applicationName << ","; - sstream << "deviceId:" << abilityInfo->deviceId << ","; - sstream << "codePath:" << abilityInfo->codePath << ","; - sstream << "resourcePath:" << abilityInfo->resourcePath << ","; - sstream << "libPath:" << abilityInfo->libPath; - return sstream.str(); -} - -std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) -{ - std::stringstream sstream; - sstream << "pid:" << processInfo->GetPid() << ","; - sstream << "processName:" << processInfo->GetProcessName(); - return sstream.str(); -} - std::vector TestUtils::split(const std::string &in, const std::string &delim) { std::regex reg(delim); std::vector res = { - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; return res; } } // 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/amsKitSystemTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h index f77383f16b8aca1809e2c3573e09ace3dff92cfc..cec4a093d9e97579b656e85fec1e7c5a6788c0d6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h @@ -113,9 +113,11 @@ public: void GetApplicationContextCase1(int code); - MainAbility() - { - mapCase_ = { + std::unordered_map>> mapCase_; + ~MainAbility(); + + void initCaseFirst() { + std::unordered_map>> first = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -146,6 +148,12 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, + }; + mapCase_.insert(first.begin(), first.end()); + } + + void initCaseSecond() { + std::unordered_map>> second = { {(int)AbilityContextApi::GetDir, { [this](int code) { GetDirCase1(code); }, @@ -188,6 +196,12 @@ public: { [this](int code) { GetContextCase1(code); }, }}, + }; + mapCase_.insert(second.begin(), second.end()); + } + + void initCaseThird() { + std::unordered_map>> third = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -232,10 +246,15 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; + mapCase_.insert(third.begin(), third.end()); } - std::unordered_map>> mapCase_; - ~MainAbility(); + MainAbility() + { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h index 2070529579d563e5202623790d100cd374851610..aa64ae6499c1fbfeda7139581bbf41881f315aca 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h @@ -115,7 +115,13 @@ public: SecondAbility() { - mapCase_ = { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } + + void initCaseFirst() { + std::unordered_map>> first = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -146,12 +152,12 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, - {(int)AbilityContextApi::GetDir, - { - [this](int code) { GetDirCase1(code); }, - [this](int code) { GetDirCase2(code); }, - [this](int code) { GetDirCase3(code); }, - }}, + }; + mapCase_.insert(first.begin(), first.end()); + } + + void initCaseSecond() { + std::unordered_map>> second = { {(int)AbilityContextApi::GetBundleManager, { [this](int code) { GetBundleManagerCase1(code); }, @@ -188,6 +194,12 @@ public: { [this](int code) { GetContextCase1(code); }, }}, + }; + mapCase_.insert(second.begin(), second.end()); + } + + void initCaseThird() { + std::unordered_map>> third = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -232,8 +244,8 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; + mapCase_.insert(third.begin(), third.end()); } - std::unordered_map>> mapCase_; int callingTime = 0; ~SecondAbility(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h index 8d2303da0503acfcbbc8b45d187b11003da431b9..64b40f888ec52c9ea73da85d972d20bc734ad447 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h @@ -34,9 +34,6 @@ public: 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::string ApplicationInfoToString(std::shared_ptr applicationInfo); - static std::string AbilityInfoToString(std::shared_ptr abilityInfo); - static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp index a4f3df5d30f4137f0d0c29a4e009327afb472098..241f5a44d2d365ad3eb31f4e323afae00b6bb164 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp @@ -20,8 +20,13 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { const int MainAbilityACode = 100; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -126,11 +131,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -150,10 +155,8 @@ void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) void MainAbility::GetApplicationInfoCase1(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -162,10 +165,8 @@ void MainAbility::GetApplicationInfoCase1(int code) void MainAbility::GetApplicationInfoCase2(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -174,10 +175,8 @@ void MainAbility::GetApplicationInfoCase2(int code) void MainAbility::GetApplicationInfoCase3(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -392,10 +391,8 @@ void MainAbility::GetAbilityManagerCase1(int code) void MainAbility::GetProcessInfoCase1(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } @@ -405,10 +402,8 @@ void MainAbility::GetProcessInfoCase1(int code) void MainAbility::GetProcessInfoCase2(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } @@ -418,10 +413,8 @@ void MainAbility::GetProcessInfoCase2(int code) void MainAbility::GetProcessInfoCase3(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp index 775f91de81484de99ad075cd034e7c56464fa541..70aa48177ed9dcee0083fe94206c63455d30d707 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp @@ -20,8 +20,13 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { const int SecondAbilityACode = 200; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -126,11 +131,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) 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) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -152,10 +157,8 @@ void SecondAbility::GetApplicationInfoCase1(int code) void SecondAbility::GetApplicationInfoCase2(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -305,10 +308,8 @@ void SecondAbility::GetProcessInfoCase1(int code) void SecondAbility::GetProcessInfoCase2(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp index 48a7ea6b0e9e382b37cda3da859643a0f2928093..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp @@ -45,85 +45,12 @@ Want TestUtils::MakeWant( return want; } -std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) -{ - std::stringstream sstream; - sstream << "name:" << applicationInfo->name << ","; - sstream << "bundleName:" << applicationInfo->bundleName << ","; - sstream << "description:" << applicationInfo->description << ","; - sstream << "iconPath:" << applicationInfo->iconPath << ","; - sstream << "label:" << applicationInfo->label << ","; - sstream << "deviceId:" << applicationInfo->deviceId << ","; - sstream << "signatureKey:" << applicationInfo->signatureKey << ","; - sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; - sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; - sstream << "supportedModes:" << applicationInfo->supportedModes << ","; - sstream << "process:" << applicationInfo->process << ","; - std::string permissions = - std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - std::string moduleSourceDirs = std::accumulate( - applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); - sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; - sstream << "entryDir:" << applicationInfo->entryDir << ","; - sstream << "codePath:" << applicationInfo->codePath << ","; - sstream << "dataDir:" << applicationInfo->dataDir << ","; - sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; - sstream << "cacheDir:" << applicationInfo->cacheDir; - return sstream.str(); -} - -std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) -{ - std::stringstream sstream; - sstream << "name:" << abilityInfo->name << ","; - sstream << "label:" << abilityInfo->label << ","; - sstream << "description:" << abilityInfo->description << ","; - sstream << "iconPath:" << abilityInfo->iconPath << ","; - sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; - sstream << "kind:" << abilityInfo->kind << ","; - auto type = static_cast::type>(abilityInfo->type); - sstream << "type:" << type << ","; - auto orientation = - static_cast::type>(abilityInfo->orientation); - sstream << "orientation:" << orientation << ","; - auto launchMode = static_cast::type>(abilityInfo->launchMode); - sstream << "launchMode:" << launchMode << ","; - std::string permissions = - std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - sstream << "process:" << abilityInfo->process << ","; - std::string deviceTypes = - std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); - sstream << "deviceTypes:" << deviceTypes << ","; - std::string deviceCapabilities = std::accumulate( - abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); - sstream << "deviceCapabilities:" << deviceCapabilities << ","; - sstream << "uri:" << abilityInfo->uri << ","; - sstream << "package:" << abilityInfo->package << ","; - sstream << "bundleName:" << abilityInfo->bundleName << ","; - sstream << "moduleName:" << abilityInfo->moduleName << ","; - sstream << "applicationName:" << abilityInfo->applicationName << ","; - sstream << "deviceId:" << abilityInfo->deviceId << ","; - sstream << "codePath:" << abilityInfo->codePath << ","; - sstream << "resourcePath:" << abilityInfo->resourcePath << ","; - sstream << "libPath:" << abilityInfo->libPath; - return sstream.str(); -} - -std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) -{ - std::stringstream sstream; - sstream << "pid:" << processInfo->GetPid() << ","; - sstream << "processName:" << processInfo->GetProcessName(); - return sstream.str(); -} - 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()}; + 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/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/amsKitSystemTestB/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h index a14c52c2f06a74ba810052457e9dfa8e9bd34477..b68fb8b68e98a7f228740a8d63dd1791fd6ae511 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h @@ -112,7 +112,14 @@ public: MainAbility() { - mapCase_ = { + initCaseFirst(); + initCaseSecond(); + initCaseThird(); + } + + void initCaseFirst() + { + std::unordered_map>> testCase = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -143,6 +150,13 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, + }; + mapCase_.insert(testCase.begin(), testCase.end()); + } + + void initCaseSecond() + { + std::unordered_map>> testCase = { {(int)AbilityContextApi::GetDir, { [this](int code) { GetDirCase1(code); }, @@ -185,6 +199,13 @@ public: { [this](int code) { GetContextCase1(code); }, }}, + }; + mapCase_.insert(testCase.begin(), testCase.end()); + } + + void initCaseThird() + { + std::unordered_map>> testCase = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -229,6 +250,7 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; + mapCase_.insert(testCase.begin(), testCase.end()); } void SubscribeEvent(); void TestAbility(int apiIndex, int caseIndex, int code); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h index 8d2303da0503acfcbbc8b45d187b11003da431b9..64b40f888ec52c9ea73da85d972d20bc734ad447 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h @@ -34,9 +34,6 @@ public: 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::string ApplicationInfoToString(std::shared_ptr applicationInfo); - static std::string AbilityInfoToString(std::shared_ptr abilityInfo); - static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp index aa08cabf14c914211188697cd65e00572460f8ea..c2411fd614d05c2998f280ec91b46e92bf1fd754 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp @@ -20,8 +20,13 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { const int MainAbilityBCode = 300; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int numThree = 3; +} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -126,11 +131,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRSTB.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -158,10 +163,8 @@ void MainAbility::GetApplicationInfoCase2(int code) void MainAbility::GetApplicationInfoCase3(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); - string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { - appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -357,10 +360,8 @@ void MainAbility::GetProcessInfoCase2(int code) void MainAbility::GetProcessInfoCase3(int code) { auto processInfo = AbilityContext::GetProcessInfo(); - string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { - processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp index 48a7ea6b0e9e382b37cda3da859643a0f2928093..07ebf00c47128276f0e83d0aa5783fec0a417147 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp @@ -45,80 +45,6 @@ Want TestUtils::MakeWant( return want; } -std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) -{ - std::stringstream sstream; - sstream << "name:" << applicationInfo->name << ","; - sstream << "bundleName:" << applicationInfo->bundleName << ","; - sstream << "description:" << applicationInfo->description << ","; - sstream << "iconPath:" << applicationInfo->iconPath << ","; - sstream << "label:" << applicationInfo->label << ","; - sstream << "deviceId:" << applicationInfo->deviceId << ","; - sstream << "signatureKey:" << applicationInfo->signatureKey << ","; - sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; - sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; - sstream << "supportedModes:" << applicationInfo->supportedModes << ","; - sstream << "process:" << applicationInfo->process << ","; - std::string permissions = - std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - std::string moduleSourceDirs = std::accumulate( - applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); - sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; - sstream << "entryDir:" << applicationInfo->entryDir << ","; - sstream << "codePath:" << applicationInfo->codePath << ","; - sstream << "dataDir:" << applicationInfo->dataDir << ","; - sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; - sstream << "cacheDir:" << applicationInfo->cacheDir; - return sstream.str(); -} - -std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) -{ - std::stringstream sstream; - sstream << "name:" << abilityInfo->name << ","; - sstream << "label:" << abilityInfo->label << ","; - sstream << "description:" << abilityInfo->description << ","; - sstream << "iconPath:" << abilityInfo->iconPath << ","; - sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; - sstream << "kind:" << abilityInfo->kind << ","; - auto type = static_cast::type>(abilityInfo->type); - sstream << "type:" << type << ","; - auto orientation = - static_cast::type>(abilityInfo->orientation); - sstream << "orientation:" << orientation << ","; - auto launchMode = static_cast::type>(abilityInfo->launchMode); - sstream << "launchMode:" << launchMode << ","; - std::string permissions = - std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); - sstream << "permissions:" << permissions << ","; - sstream << "process:" << abilityInfo->process << ","; - std::string deviceTypes = - std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); - sstream << "deviceTypes:" << deviceTypes << ","; - std::string deviceCapabilities = std::accumulate( - abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); - sstream << "deviceCapabilities:" << deviceCapabilities << ","; - sstream << "uri:" << abilityInfo->uri << ","; - sstream << "package:" << abilityInfo->package << ","; - sstream << "bundleName:" << abilityInfo->bundleName << ","; - sstream << "moduleName:" << abilityInfo->moduleName << ","; - sstream << "applicationName:" << abilityInfo->applicationName << ","; - sstream << "deviceId:" << abilityInfo->deviceId << ","; - sstream << "codePath:" << abilityInfo->codePath << ","; - sstream << "resourcePath:" << abilityInfo->resourcePath << ","; - sstream << "libPath:" << abilityInfo->libPath; - return sstream.str(); -} - -std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) -{ - std::stringstream sstream; - sstream << "pid:" << processInfo->GetPid() << ","; - sstream << "processName:" << processInfo->GetProcessName(); - return sstream.str(); -} - std::vector TestUtils::split(const std::string &in, const std::string &delim) { std::regex reg{delim}; 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..a051169e093b7b5aed208403a0f3f7851a47861b --- 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\"", @@ -59,13 +60,19 @@ ohos_shared_library("amsKitSystemTestDataA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//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", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", ] subsystem_name = "amssystemtestability" } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h index b7b0e3a0109dfe8e31378671ea3231f1e3ae536a..9f08a10eadce1a266f308b5656af3faac2570d60 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a1.h @@ -24,6 +24,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -52,11 +55,11 @@ protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h index 567be45bbbb6e5bb8391b268897bfdc26c407799..aa9e88cc6fa423408bbdae42f57f2e2e402fd51c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a2.h @@ -24,6 +24,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -52,11 +55,11 @@ protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h index 71a18a1da559871e689640ab1f84e7dfa62b3409..a5ad84581010067265754573ccca37835d1adcd6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/include/ams_st_kit_data_ability_data_a3.h @@ -24,6 +24,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -52,11 +55,11 @@ protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp index 90924e5db44ca23ef89a24dfbd4392df256bdf9f..fdefb6df2f6e9619bad16983f9adad553d33f961 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 250; static const int LIFECYCLE_CALLBACKS = 251; static const int LIFECYCLE_OBSERVER = 252; @@ -40,6 +41,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -259,14 +262,14 @@ void AmsStKitDataAbilityDataA1::OnNewWant(const Want &want) PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnNewWant"); } -int AmsStKitDataAbilityDataA1::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStKitDataAbilityDataA1::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); return DEFAULT_INSERT_RESULT; } -int AmsStKitDataAbilityDataA1::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStKitDataAbilityDataA1::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); @@ -274,15 +277,15 @@ int AmsStKitDataAbilityDataA1::Delete(const Uri &uri, const DataAbilityPredicate } int AmsStKitDataAbilityDataA1::Update( - const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStKitDataAbilityDataA1::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStKitDataAbilityDataA1::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); @@ -291,7 +294,9 @@ std::shared_ptr AmsStKitDataAbilityDataA1::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -299,7 +304,7 @@ std::vector AmsStKitDataAbilityDataA1::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -334,8 +339,8 @@ void AmsStKitDataAbilityDataA1::TestLifeCycle() static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityDataA1 *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -345,8 +350,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -360,9 +369,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -380,7 +390,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA1EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp index b7fa06d391523f02b905b0e13c7989c4c8f69f39..0e91ff0e269bcd4e2deed06408c4fb23fa01ef05 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 260; static const int LIFECYCLE_CALLBACKS = 261; static const int LIFECYCLE_OBSERVER = 262; @@ -38,6 +39,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -256,14 +259,14 @@ void AmsStKitDataAbilityDataA2::OnNewWant(const Want &want) PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnNewWant"); } -int AmsStKitDataAbilityDataA2::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStKitDataAbilityDataA2::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); return DEFAULT_INSERT_RESULT; } -int AmsStKitDataAbilityDataA2::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStKitDataAbilityDataA2::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); @@ -271,15 +274,15 @@ int AmsStKitDataAbilityDataA2::Delete(const Uri &uri, const DataAbilityPredicate } int AmsStKitDataAbilityDataA2::Update( - const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStKitDataAbilityDataA2::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStKitDataAbilityDataA2::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); @@ -288,7 +291,9 @@ std::shared_ptr AmsStKitDataAbilityDataA2::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -296,7 +301,7 @@ std::vector AmsStKitDataAbilityDataA2::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -333,8 +338,8 @@ void AmsStKitDataAbilityDataA2::TestLifeCycle() static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityDataA2 *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -344,8 +349,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -359,9 +368,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -372,7 +382,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA2EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp index a56dcf79f7d80b4aeaa4e023d9fcc2f60b7c13e3..e74af5a4be66fef6580fbbd08b011356ef1ac03f 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 290; static const int LIFECYCLE_CALLBACKS = 291; static const int LIFECYCLE_OBSERVER = 292; @@ -38,6 +39,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -259,14 +262,14 @@ void AmsStKitDataAbilityDataA3::OnNewWant(const Want &want) PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnNewWant"); } -int AmsStKitDataAbilityDataA3::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStKitDataAbilityDataA3::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); return DEFAULT_INSERT_RESULT; } -int AmsStKitDataAbilityDataA3::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStKitDataAbilityDataA3::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); @@ -274,15 +277,15 @@ int AmsStKitDataAbilityDataA3::Delete(const Uri &uri, const DataAbilityPredicate } int AmsStKitDataAbilityDataA3::Update( - const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) + const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStKitDataAbilityDataA3::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStKitDataAbilityDataA3::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); @@ -291,7 +294,9 @@ std::shared_ptr AmsStKitDataAbilityDataA3::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -299,7 +304,7 @@ std::vector AmsStKitDataAbilityDataA3::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -336,8 +341,8 @@ void AmsStKitDataAbilityDataA3::TestLifeCycle() static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityDataA3 *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -347,8 +352,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -362,9 +371,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -375,7 +385,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA3EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp index 68c42c58f06ba15bfd89f1e044427915605b60b1..a56a0c4d77a97fee280b49e121dbfe867ffe0664 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp @@ -20,12 +20,13 @@ #include "app_log_wrapper.h" #include "data_ability_helper.h" -#include "dummy_data_ability_predicates.h" -#include "dummy_result_set.h" -#include "dummy_values_bucket.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_CODE = 130; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityPageA::~AmsStKitDataAbilityPageA() void AmsStKitDataAbilityPageA::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -133,7 +136,7 @@ void AmsStKitDataAbilityPageA::OnBackground() void AmsStKitDataAbilityPageA::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -149,8 +152,8 @@ void AmsStKitDataAbilityPageA::GetWantInfo(const Want &want) static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityPageA *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -160,8 +163,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -175,9 +182,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -189,7 +197,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestPageAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestPageAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp index 17140dc40642fc1b1ec6159f045593c92402a380..764709751a59e1be249ca1bba90eebc5de3bb08f 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp @@ -20,12 +20,13 @@ #include "app_log_wrapper.h" #include "data_ability_helper.h" -#include "dummy_data_ability_predicates.h" -#include "dummy_result_set.h" -#include "dummy_values_bucket.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_SERVICE_CODE = 310; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityServiceA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityServiceA::~AmsStKitDataAbilityServiceA() void AmsStKitDataAbilityServiceA::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -159,7 +162,7 @@ void AmsStKitDataAbilityServiceA::OnDisconnect(const Want &want) void AmsStKitDataAbilityServiceA::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -175,8 +178,8 @@ void AmsStKitDataAbilityServiceA::GetWantInfo(const Want &want) static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityServiceA *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -186,8 +189,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -201,9 +208,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; + char str[charCnt]; if (!feof(file)) - fgets(str, 5, file); + fgets(str, charCnt, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -215,7 +222,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestServiceAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { 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..0006d0fdecc17b8b003284595c2644266d7c9c3a --- 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\"", @@ -57,13 +58,19 @@ ohos_shared_library("amsKitSystemTestDataB") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//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", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", ] subsystem_name = "amssystemtestability" } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h index 4732d61bae3e8a7cfe4de37916c43c6c531b7164..964081eaa8738720fe6f3e6d759be298073038bb 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_data_b.h @@ -24,6 +24,9 @@ #include "event.h" #include "skills.h" #include "stoperator.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { @@ -51,11 +54,11 @@ protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) 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 int Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) override; + virtual int Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual int Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) override; + virtual std::shared_ptr Query( + const Uri &uri, const std::vector &columns, const NativeRdb::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; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h index 7a355e5d75a21626c64f055579ee8570126e791d..d52b7ef6ce72247748f3b459600f90106a3fed2c 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h @@ -58,11 +58,13 @@ public: KitTestPageBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityPageB *ability) : CommonEventSubscriber(sp) { - mapTestFunc_ = {{"OnStart", [this]() { TestPost("OnStart"); }}, + mapTestFunc_ = { + {"OnStart", [this]() { TestPost("OnStart"); }}, {"OnStop", [this]() { TestPost("OnStop"); }}, {"OnActive", [this]() { TestPost("OnActive"); }}, {"OnInactive", [this]() { TestPost("OnInactive"); }}, - {"OnBackground", [this]() { TestPost("OnBackground"); }}}; + {"OnBackground", [this]() { TestPost("OnBackground"); }} + }; mainAbility_ = ability; }; virtual void OnReceiveEvent(const CommonEventData &data); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp index b79c784dc0bdc4f280fac7a986826b8f9289ebd4..da3b1af7b45832565c8bd91cbceae25cedf1b8e4 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_DATA_CODE = 270; static const int LIFECYCLE_CALLBACKS = 271; static const int LIFECYCLE_OBSERVER = 272; @@ -38,6 +39,8 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; +constexpr int charCnt = 5; +} void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -257,29 +260,29 @@ void AmsStKitDataAbilityDataB::OnBackground() PublishEvent(abilityEventName, ABILITY_DATA_CODE, "OnBackground"); } -int AmsStKitDataAbilityDataB::Insert(const Uri &uri, const ValuesBucket &value) +int AmsStKitDataAbilityDataB::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Insert"); return DEFAULT_INSERT_RESULT; } -int AmsStKitDataAbilityDataB::Delete(const Uri &uri, const DataAbilityPredicates &predicates) +int AmsStKitDataAbilityDataB::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Delete"); return DEFAULT_DELETE_RESULT; } -int AmsStKitDataAbilityDataB::Update(const Uri &uri, const ValuesBucket &value, const DataAbilityPredicates &predicates) +int AmsStKitDataAbilityDataB::Update(const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "Update"); return DEFAULT_UPDATE_RESULT; } -std::shared_ptr AmsStKitDataAbilityDataB::Query( - const Uri &uri, const std::vector &columns, const DataAbilityPredicates &predicates) +std::shared_ptr AmsStKitDataAbilityDataB::Query( + const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { subscriber_->vectorOperator_ = columns; APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); @@ -288,7 +291,9 @@ std::shared_ptr AmsStKitDataAbilityDataB::Query( STtools::WaitCompleted(event, OPERATOR_QUERY, ABILITY_DATA_CODE); subscriber_->TestPost(); - std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + std::shared_ptr resultValue = std::make_shared(OPERATOR_QUERY); + AppDataFwk::SharedBlock *pSharedBlock = resultValue->GetBlock(); + pSharedBlock->PutString(0, 0, OPERATOR_QUERY.c_str(), OPERATOR_QUERY.size() + 1); return resultValue; } @@ -296,7 +301,7 @@ std::vector AmsStKitDataAbilityDataB::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType{"filetypes"}; + std::vector fileType {"filetypes"}; return fileType; } @@ -316,8 +321,8 @@ int AmsStKitDataAbilityDataB::OpenFile(const Uri &uri, const std::string &mode) static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityDataB *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -327,8 +332,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -342,9 +351,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -356,7 +366,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestDataBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp index 8deb7457a7bb9144a5deb9af5e4d4fafa320e726..8cb4ff8d39778fbe7cf54a303866c9c6f06d72bf 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp @@ -20,12 +20,13 @@ #include "data_ability_helper.h" #include "app_log_wrapper.h" -#include "dummy_values_bucket.h" -#include "dummy_data_ability_predicates.h" -#include "dummy_result_set.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_PAGE_CODE = 140; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityPageB::~AmsStKitDataAbilityPageB() void AmsStKitDataAbilityPageB::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -133,7 +136,7 @@ void AmsStKitDataAbilityPageB::OnBackground() void AmsStKitDataAbilityPageB::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -149,8 +152,8 @@ void AmsStKitDataAbilityPageB::GetWantInfo(const Want &want) static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityPageB *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -160,8 +163,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -175,9 +182,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -189,7 +197,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestPageBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestPageBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp index 438db44dcbef83ec7a8da81836eff73d75ee8921..8e6115af0adaf5211af0f1a438da442d1f7aedc1 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp @@ -20,12 +20,13 @@ #include "data_ability_helper.h" #include "app_log_wrapper.h" -#include "dummy_values_bucket.h" -#include "dummy_data_ability_predicates.h" -#include "dummy_result_set.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" namespace OHOS { namespace AppExecFwk { +namespace { static const int ABILITY_SERVICE_CODE = 320; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,6 +35,8 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; +constexpr int charCnt = 5; +} bool AmsStKitDataAbilityServiceB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -70,7 +73,7 @@ AmsStKitDataAbilityServiceB::~AmsStKitDataAbilityServiceB() void AmsStKitDataAbilityServiceB::SubscribeEvent(const Want &want) { - Want mwant{want}; + Want mwant {want}; std::vector eventList = { "event_data_test_action", }; @@ -159,7 +162,7 @@ void AmsStKitDataAbilityServiceB::OnDisconnect(const Want &want) void AmsStKitDataAbilityServiceB::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -175,8 +178,8 @@ void AmsStKitDataAbilityServiceB::GetWantInfo(const Want &want) static void GetResult(std::shared_ptr child, std::shared_ptr helper, AmsStKitDataAbilityServiceB *mainAbility, Uri dataAbilityUri, string &result) { - AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + NativeRdb::DataAbilityPredicates predicates; + NativeRdb::ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -186,8 +189,12 @@ static void GetResult(std::shared_ptr child, std::shared_pt result = std::to_string(helper->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { std::vector columns = STtools::SerializationStOperatorToVector(*child); - std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); - result = (resultValue != nullptr) ? (resultValue->testInf_) : "failed"; + std::shared_ptr resultValue = helper->Query(dataAbilityUri, columns, predicates); + result = "failed"; + if (resultValue != nullptr) { + resultValue->GoToRow(0); + resultValue->GetString(0, result); + } } else if (child->GetOperatorName() == OPERATOR_GETFILETYPES) { std::vector types = helper->GetFileTypes(dataAbilityUri, child->GetMessage()); result = (types.size() > 0) ? types[0] : "failed"; @@ -201,9 +208,10 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[5]; - if (!feof(file)) - fgets(str, 5, file); + char str[charCnt]; + if (!feof(file)) { + fgets(str, charCnt, file); + } result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -215,7 +223,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestServiceBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator{}; + STtools::StOperator allOperator {}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { 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/amsKitSystemTestPageA/include/ability_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h index f44e0b2f3da20ae0c371d5f7751ff5528c591fbf..718947b23185185e16edccb4cb22e552b489e69e 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h @@ -87,7 +87,8 @@ public: bool SubscribeEvent(); void DoTestCase(); void StopSelfAbility(); - + void caseIndexOne(); + void caseIndexTwo(); protected: virtual void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h index 066c3eb55bd293fc92c93c75b476955daba8f827..73bd3364feef69df4a5cad290b3f8a9a910faab7 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class ServiceLifecycleCallbacks : public AbilityLifecycleCallbacks { public: ServiceLifecycleCallbacks() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp index 0060598daaf505785786a261d9e5cc0399dc428d..f08aeff55b00611e962d1a36d3cde6f40980dc7d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp @@ -709,6 +709,28 @@ void AbilityAbility::TestAbilityGetLifecycle() } } +void AbilityAbility::caseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::caseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); + +} + void AbilityAbility::TestAbilityDisconnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -717,23 +739,10 @@ void AbilityAbility::TestAbilityDisconnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + caseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + caseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp index 08ef9ee33f6c7062c3dd4ed8948a80f9e7b0fe77..c2552fa710c22685e4eb5522b129f6a26d306081 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp @@ -21,6 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int loopCnt = 3; +} // namespace AbilityLifeCycleAbility::~AbilityLifeCycleAbility() { @@ -228,7 +231,7 @@ void AbilityLifeCycleAbility::TestStopAbility() TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { bool ret = BaseAbility::GetContext()->StopAbility(want_); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp index 4653d6331658f05a5129de9aa650f8bde6772b8f..5ae57412319b7807964d5405c0d3e27c6077a904 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp @@ -21,7 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { +constexpr int loopCnt = 100; +} void LifecycleObserverLifecycleObserver::DoTask() { switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { @@ -492,7 +494,7 @@ void LifeCycleObserverAbility::TestLifeCycleGetLifecycle() TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); } break; case CaseIndex::TWO: { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < loopCnt; i++) { auto lifecycle = GetLifecycle(); } TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); 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/amsKitSystemTestService/include/ability_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h index 17c36f5b4ffd1112102dec0663e63381323918e7..ef28fca50f763afcf800619f687b6aa6b2d984d6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_ability.h @@ -83,7 +83,12 @@ public: void TestAbilityDisconnectAbility(); void DoTestCase(); - + void CaseIndexOne(); + void CaseIndexTwo(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); + void AbilityDisconnectCaseIndexOne(); + void AbilityDisconnectCaseIndexTwo(); protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) override; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h index ca235dbdb8c4003374fb490dd3581e4b75207ec4..e094e4e8de820cde094d854c6f0bf8aa958ff391 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_connection_ability.h @@ -80,6 +80,10 @@ public: void TestDisconnectAbility(); void TestStartAbility(); void TestTerminateAbility(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); + void ConnectCaseIndexOne(); + void ConnectCaseIndexTwo(); protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, @@ -97,9 +101,9 @@ protected: bool SubscribeEvent(); private: - Want want_{}; - sptr stub_{}; - sptr connCallback_{}; + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; std::shared_ptr subscriber_ = {}; }; std::string AbilityConnectionAbility::sequenceNumber_ = "0"; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h index c2b76b14efc988ff420094b82f52544adeb0d6bd..95242ba347f1be9ed20933f0cd0c2d457839f4cf 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_context_ability.h @@ -90,11 +90,14 @@ protected: virtual void OnDisconnect(const Want &want) override; bool SubscribeEvent(); - + void ConnectCaseIndexOne(); + void ConnectCaseIndexTwo(); + void DisconnectCaseIndexOne(); + void DisconnectCaseIndexTwo(); private: - Want want_{}; - sptr stub_{}; - sptr connCallback_{}; + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; std::shared_ptr subscriber_ = {}; }; int AbilityContextAbility::sequenceNumber_ = 0; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h index 3adcabb8db4d64832bfe72f1115abea51b151bcb..c52ea2d40fb21a629e02b4fe8b74c2109d575e1a 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/ability_life_cycle_ability.h @@ -113,11 +113,11 @@ protected: virtual void OnDisconnect(const Want &want) override; bool SubscribeEvent(); - + void GetLifecycleStateCaseOne(); private: - Want want_{}; - sptr stub_{}; - sptr connCallback_{}; + Want want_ {}; + sptr stub_ {}; + sptr connCallback_ {}; std::shared_ptr subscriber_ = {}; }; int AbilityLifeCycleAbility::sequenceNumber_ = 0; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h index 0da1ab05da2138a591f56d048161a79f2ee1e8fa..25b50672cc6ccd0204e7778a4a3b9143926d6f86 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/include/life_cycle_call_backs_ability.h @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { - class ServiceLifecycleCallbacks : public AbilityLifecycleCallbacks { public: ServiceLifecycleCallbacks() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp index 282f42fe45e218f19a4991b215f1e308d294083c..f0756aa5f352d2b5d723138a2694d3077f136eef 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_ability.cpp @@ -20,6 +20,10 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int SLEEP_SECOND = 2; +constexpr int loopCnt = 3; +} AbilityAbility::~AbilityAbility() { @@ -174,6 +178,27 @@ void AbilityAbility::OnNewWant(const Want &want) DoTestCase(); } +void AbilityAbility::CaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::CaseIndexTwo() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + DisconnectAbility(connCallback_); +} + void AbilityAbility::TestConnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -182,23 +207,10 @@ void AbilityAbility::TestConnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); - DisconnectAbility(connCallback_); + CaseIndexOne(); } break; case CaseIndex::TWO: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); - DisconnectAbility(connCallback_); + CaseIndexTwo(); } break; case CaseIndex::THREE: { stub_ = new (std::nothrow) AbilityConnectCallback(); @@ -207,7 +219,7 @@ void AbilityAbility::TestConnectAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); bool ret = ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { @@ -216,7 +228,7 @@ void AbilityAbility::TestConnectAbility() connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); bool ret = ConnectAbility(want_, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } } break; @@ -225,7 +237,7 @@ void AbilityAbility::TestConnectAbility() sptr connCallback(new (std::nothrow) AbilityConnectionProxy(stub)); bool ret = ConnectAbility(want_, connCallback); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback); } break; default: @@ -258,7 +270,7 @@ void AbilityAbility::TestStopAbility() TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { bool ret = StopAbility(want_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestStopAbility"); } @@ -275,6 +287,25 @@ void AbilityAbility::TestStopAbility() } } +void AbilityAbility::DisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::DisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + DisconnectAbility(connCallback_); +} + void AbilityAbility::TestDisconnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -283,21 +314,10 @@ void AbilityAbility::TestDisconnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - DisconnectAbility(connCallback_); + DisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - DisconnectAbility(connCallback_); + DisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; @@ -309,7 +329,7 @@ void AbilityAbility::TestDisconnectAbility() DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { stub_ = new (std::nothrow) AbilityConnectCallback(); connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); bool ret = ConnectAbility(want_, connCallback_); @@ -391,7 +411,7 @@ void AbilityAbility::TestTerminateAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); StopAbility(want); TerminateAbility(); } break; @@ -400,7 +420,7 @@ void AbilityAbility::TestTerminateAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); StopAbility(want); TerminateAbility(); } break; @@ -415,7 +435,7 @@ void AbilityAbility::TestTerminateAbility() Want want = TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKitx", params); StartAbility(want, 0); - sleep(2); + sleep(SLEEP_SECOND); TerminateAbility(); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, 1, "TestTerminateAbility"); } break; @@ -491,7 +511,7 @@ void AbilityAbility::TestAbilityConnectAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); bool ret = ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } break; case CaseIndex::THREE: { @@ -501,7 +521,7 @@ void AbilityAbility::TestAbilityConnectAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); bool ret = ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityConnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { @@ -612,6 +632,27 @@ void AbilityAbility::TestAbilityGetLifecycle() } } +void AbilityAbility::AbilityDisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + +void AbilityAbility::AbilityDisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); +} + void AbilityAbility::TestAbilityDisconnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -620,23 +661,10 @@ void AbilityAbility::TestAbilityDisconnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + AbilityDisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); + AbilityDisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp index 054b04669acaa7d7c808ca49da9d3704de411e18..3f9ec8825d16e5390731a75cc128e40867229178 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_connection_ability.cpp @@ -126,27 +126,35 @@ void AbilityConnectionAbility::OnDisconnect(const Want &want) APP_ABILITY_CONNECTION_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); } +void AbilityConnectionAbility::ConnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::ConnectCaseIndexTwo() { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityConnectionAbility::TestConnectAbility() { switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexOne(); } break; case CaseIndex::TWO: { - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexTwo(); } break; case CaseIndex::THREE: { stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); @@ -219,27 +227,35 @@ void AbilityConnectionAbility::TestStopAbility() } } +void AbilityConnectionAbility::DisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityConnectionAbility::DisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityConnectionAbility::TestDisconnectAbility() { switch ((CaseIndex)std::stoi(AbilityConnectionAbility::sequenceNumber_)) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectionConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONNECTION_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp index a8155eda53fa557102b5fafde57d0a89a26506d7..9f53b7f6cbb8f674077bc3026df7a992d2affacb 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_context_ability.cpp @@ -21,6 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int SLEEP_SECOND = 2; +} AbilityContextAbility::~AbilityContextAbility() { @@ -127,27 +130,35 @@ void AbilityContextAbility::OnDisconnect(const Want &want) APP_ABILITY_CONTEXT_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); } +void AbilityContextAbility::ConnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::ConnectCaseIndexTwo() { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); + sleep(1); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityContextAbility::TestConnectAbility() { switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(2); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexOne(); } break; case CaseIndex::TWO: { - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestConnectAbility"); - sleep(1); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + ConnectCaseIndexTwo(); } break; case CaseIndex::THREE: { stub_ = new (std::nothrow) AbilityContextConnectCallback(); @@ -220,26 +231,34 @@ void AbilityContextAbility::TestStopAbility() } } +void AbilityContextAbility::DisconnectCaseIndexOne() { + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + +void AbilityContextAbility::DisconnectCaseIndexTwo() { + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityContextConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); + sleep(SLEEP_SECOND); + BaseAbility::GetContext()->DisconnectAbility(connCallback_); +} + void AbilityContextAbility::TestDisconnectAbility() { switch ((CaseIndex)AbilityContextAbility::sequenceNumber_) { case CaseIndex::ONE: { - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexOne(); } break; case CaseIndex::TWO: { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityContextConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(2); - BaseAbility::GetContext()->DisconnectAbility(connCallback_); + DisconnectCaseIndexTwo(); } break; case CaseIndex::THREE: { MAP_STR_STR params; @@ -248,7 +267,7 @@ void AbilityContextAbility::TestDisconnectAbility() connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); bool ret = BaseAbility::GetContext()->ConnectAbility(want, connCallback_); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestDisconnectAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->DisconnectAbility(connCallback_); } break; case CaseIndex::FOUR: { @@ -288,7 +307,7 @@ void AbilityContextAbility::TestStartAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); } break; case CaseIndex::THREE: { @@ -296,7 +315,7 @@ void AbilityContextAbility::TestStartAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestStartAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); } break; case CaseIndex::FOUR: { @@ -330,7 +349,7 @@ void AbilityContextAbility::TestTerminateAbility() TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); BaseAbility::GetContext()->TerminateAbility(); } break; @@ -339,7 +358,7 @@ void AbilityContextAbility::TestTerminateAbility() Want want = TestUtils::MakeWant("", "AmsStServiceAbilityA1", "com.ohos.amsst.service.appA", params); BaseAbility::GetContext()->StartAbility(want, 0); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, 1, "TestTerminateAbility"); - sleep(2); + sleep(SLEEP_SECOND); BaseAbility::GetContext()->StopAbility(want); BaseAbility::GetContext()->TerminateAbility(); } break; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp index 2ccf0e524b6942032336966c424453110b96db11..03392a73520f1f13c2aafdfd5921a519a9e37cb6 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/ability_life_cycle_ability.cpp @@ -21,7 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { +constexpr int loopCnt = 3; +} AbilityLifeCycleAbility::~AbilityLifeCycleAbility() { CommonEventManager::UnSubscribeCommonEvent(subscriber_); @@ -234,7 +236,7 @@ void AbilityLifeCycleAbility::TestStopAbility() TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); } break; case CaseIndex::FOUR: { - for (int i = 0; i < 3; i++) { + for (int i = 0; i < loopCnt; i++) { bool ret = BaseAbility::GetContext()->StopAbility(want_); TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, ret, "TestStopAbility"); } @@ -420,14 +422,18 @@ void AbilityLifeCycleAbility::TestLifeCycleGetLifecycle() } } +void AbilityLifeCycleAbility::GetLifecycleStateCaseOne() { + auto lifecycle = GetLifecycle(); + TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, + lifecycle->GetLifecycleState(), + "TestLifeCycleGetLifecycleState"); +} + void AbilityLifeCycleAbility::TestLifeCycleGetLifecycleState() { switch ((CaseIndex)AbilityLifeCycleAbility::sequenceNumber_) { case CaseIndex::ONE: { - auto lifecycle = GetLifecycle(); - TestUtils::PublishEvent(APP_ABILITY_LIFE_CYCLE_RESP_EVENT_NAME, - lifecycle->GetLifecycleState(), - "TestLifeCycleGetLifecycleState"); + GetLifecycleStateCaseOne(); } break; case CaseIndex::TWO: { auto lifecycle = GetLifecycle(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp index 4a61746250ba165767f53646d896a910b1ce877a..a5559b0e1be5f0e2a32352b3690bb12496a31ea3 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestService/src/life_cycle_observer_ability.cpp @@ -21,7 +21,9 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; - +namespace { +constexpr int loopCnt = 100; +} void LifecycleObserverLifecycleObserver::DoTask() { switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { @@ -491,7 +493,7 @@ void LifeCycleObserverAbility::TestLifeCycleGetLifecycle() TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); } break; case CaseIndex::TWO: { - for (int i = 0; i < 100; i++) { + for (int i = 0; i < loopCnt; i++) { auto lifecycle = GetLifecycle(); } TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); 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..4084128d4e1da62e91814663c6cb68ddf9ba9415 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/main_ability.cpp @@ -0,0 +1,334 @@ +/* + * 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; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +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() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), 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(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..7c56b71123e1fe14ba2002a5804f6eef2e3dd791 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/second_ability.cpp @@ -0,0 +1,293 @@ +/* + * 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; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +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() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), 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..59b7c1e79338b68ca791c1def3e16f89fc0b4b27 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTest/src/third_ability.cpp @@ -0,0 +1,240 @@ +/* + * 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; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +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() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), 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..58342d5889c81e84c05af532282694b2f51c5254 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/include/third_ability.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 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); + + ThirdAbility() + { + mapCase_ = {}; + } + + 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_ = {}; + 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..1494ddd3b7a09eeaa4194fd7968f4e7ec230b612 --- /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; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +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"; + 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"; + 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() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), 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..913eedc54acf04cf9521dd87979d5fba5a070e8a --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/second_ability.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 "second_ability.h" +#include "app_log_wrapper.h" +#include "test_utils.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS::EventFwk; +using namespace OHOS::AAFwk; +constexpr int index_f = 0; +constexpr int index_s = 1; +constexpr int index_t = 2; +constexpr int paramCnt = 3; + +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"; + 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"; + 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() < paramCnt) { + return; + } + if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), 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; + TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); +} + +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..b15f3e21b415e1e4ce0bc37358fc6153e595080e --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/amsMissionStackTestSubsidiary/src/third_ability.cpp @@ -0,0 +1,134 @@ +/* + * 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(); +} + +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); + } + } +} + +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/amsstabilityr2.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp index 1d8adb99f27e3a6905e5e98e42811ade74e6ea27..75ee4caf3814631de34dbb08c63dbaf3f6fd4de0 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr2.cpp @@ -17,6 +17,9 @@ namespace OHOS { namespace AppExecFwk { +namespace { +constexpr uint32_t multiple = 100; +} void AmsStAbilityR2::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -98,7 +101,7 @@ void AmsStAbilityR2::OnBackground() { APP_LOGI("AmsStAbilityR2::OnBackground"); Ability::OnBackground(); - std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::BACKGROUND_TIMEOUT * 100)); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::BACKGROUND_TIMEOUT * multiple)); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp index 32c656679b2e74f040336318f217a332dbc0eede..f8c1476c1f0dde14e73b3e2965135e2c0cd9992f 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsSystemTestR/src/amsstabilityr3.cpp @@ -17,6 +17,9 @@ namespace OHOS { namespace AppExecFwk { +namespace { +constexpr uint32_t timeoutAdd = 5000; +} void AmsStAbilityR3::OnStart(const Want &want) { GetWantInfo(want); @@ -88,7 +91,7 @@ void AmsStAbilityR3::OnBackground() { APP_LOGI("AmsStAbilityR3::OnBackground"); Ability::OnBackground(); - std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::TERMINATE_TIMEOUT + 5000)); + std::this_thread::sleep_for(std::chrono::milliseconds(STEventName::TERMINATE_TIMEOUT + timeoutAdd)); std::string eventData = GetAbilityName() + STEventName::g_abilityStateOnBackground; pageAbilityEvent.PublishEvent(STEventName::g_eventName, pageAbilityEvent.GetOnBackgroundCount(), eventData); } 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..939b33dde92eb9900f3276b75ce9245fcfa44d9e 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,16 @@ 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/common/kit_test_common_info.h b/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h index ab1dc4dc870e2d7fea5386e9d8d5068865e196b3..c6c6a41b6da9ff4523451eb9f2c11ce93e5583ef 100644 --- a/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h +++ b/test/resource/amssystemtestability/abilitySrc/common/kit_test_common_info.h @@ -423,7 +423,6 @@ enum class WantParamsApi { SetParam, End, }; - } // namespace AppExecFwk } // namespace OHOS #endif // KIT_TEST_COMMON_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..48185c7a6897217fb45ceae95fe93a2bf295213a --- /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_SERVICE_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..dc7d251fad6cee116e41959877f80dc36d42e573 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/test_ability_connect_callback_stub.h @@ -0,0 +1,44 @@ +/* + * 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; + +private: + DISALLOW_COPY_AND_MOVE(TestAbilityConnectionStub); +}; + +} // 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..c13a82e29e87f954555119bb80dd24b3f8e70028 --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h @@ -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. + */ + +#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..4ce9fb75ee8ff71a58365d5b51a4b87a55dfbcbd --- /dev/null +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/src/test_ability_connect_callback_stub.cpp @@ -0,0 +1,146 @@ + +/* + * 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; + } + + 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.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; + } + default: { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } +} + +} // 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/taskDispatcherTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h index e32f3c5521a3b852d7224e2e63db851c71226d23..f0ffaa195385b9f13d7fb5035a070d365485fe00 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/include/test_utils.h @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - class TestUtils { public: TestUtils() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp index cd1ad9aae0224f465a5bfd66f992b5a8092284da..af5f914a38845d242af4ba3e827e95d9a2afe44a 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp @@ -27,7 +27,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::STtools; - +namespace { int terminated_task_num = 0; std::condition_variable cv; std::mutex cv_mutex; @@ -48,6 +48,11 @@ std::string innerDelimiter = "-"; std::string task_execution_sequence = delimiter; std::vector> allDispatchers; std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} bool Wait(const int task_num) { @@ -360,14 +365,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[0]=%{public}s", caseInfo[0].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[1]=%{public}s", caseInfo[1].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[2]=%{public}s", caseInfo[2].c_str()); - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -383,72 +385,41 @@ void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) } } -int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) -{ - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch begin"); - std::string outerName = "outerDispatcher"; - std::string innerName = "innerDispatcher"; +void SetInnerTask(TaskList innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) { + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} - std::string outerTaskId; - auto context = GetContext(); - TaskList outerDispatcher{outerSetting.dispatcher, context, outerName}; - if (outerSetting.create_group) { - outerDispatcher.addOperation(TestOperation::CREATE_GROUP); +void SetInnerTaskOther(TaskList innerDispatcher, TestSetting innerSetting, int outerTaskSeq) { + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); } - for (int i = 0; i < testTaskCount; i++) { - outerTaskId = std::to_string(i); - auto outerTask = std::make_shared([=]() { - auto context = this->GetContext(); - TaskList innerDispatcher{innerSetting.dispatcher, context, innerName + std::to_string(i)}; - if (innerSetting.create_group) { - innerDispatcher.addOperation(TestOperation::CREATE_GROUP); - } - for (int j = 0; j < testTaskCount; j++) { - std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(j); - auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); - innerDispatcher.addOperation(innerSetting.op); - if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { - innerDispatcher.addApply(innerSetting.apply); - } - if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { - innerDispatcher.addDelay(innerSetting.delay); - } - innerDispatcher.addFunc(innerTask); - } - if (innerSetting.sync_barrier) { - std::string taskId = innerSyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (innerSetting.async_barrier) { - std::string taskId = innerAsyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (innerSetting.group_wait) { - innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); - } - if (innerSetting.group_notify) { - std::string taskId = innerGroupNotifyId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); - } - innerDispatcher.executedTask(); - { - std::lock_guard lock(dispatcher_mutex); - allDispatchers.push_back(innerDispatcher.getDispatcher()); - } - TestTask(outerTaskId); - }); - outerDispatcher.addOperation(outerSetting.op); - if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { - outerDispatcher.addApply(outerSetting.apply); - } - if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { - outerDispatcher.addDelay(outerSetting.delay); - } - outerDispatcher.addFunc(outerTask); + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList outerDispatcher, TestSetting outerSetting) { if (outerSetting.sync_barrier) { auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); @@ -464,11 +435,9 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); } - outerDispatcher.executedTask(); - { - std::lock_guard lock(dispatcher_mutex); - allDispatchers.push_back(outerDispatcher.getDispatcher()); - } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) { int taskCount = 0; taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; if (innerSetting.sync_barrier) { @@ -492,7 +461,54 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) if (outerSetting.group_notify) { taskCount++; } - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch end taskCount:%{public}d", taskCount); + return taskCount; +} + +int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) +{ + std::string outerName = "outerDispatcher"; + std::string innerName = "innerDispatcher"; + std::string outerTaskId; + auto context = GetContext(); + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; + if (outerSetting.create_group) { + outerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int i = 0; i < testTaskCount; i++) { + outerTaskId = std::to_string(i); + auto outerTask = std::make_shared([=]() { + auto context = this->GetContext(); + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; + if (innerSetting.create_group) { + innerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int j = 0; j < testTaskCount; j++) { + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); + } + SetInnerTaskOther(innerDispatcher, innerSetting, i); + innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } + TestTask(outerTaskId); + }); + outerDispatcher.addOperation(outerSetting.op); + if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { + outerDispatcher.addApply(outerSetting.apply); + } + if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { + outerDispatcher.addDelay(outerSetting.delay); + } + outerDispatcher.addFunc(outerTask); + } + SetOuterTaskOther(outerDispatcher, outerSetting); + outerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); return taskCount; } @@ -1820,7 +1836,6 @@ void MainAbility::GlobalCase50(int code) // level1:global, group level2:serial, delay void MainAbility::GlobalCase51(int code) { - APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); TestSetting outerSetting; @@ -8973,7 +8988,7 @@ void MainAbility::HybridCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9003,7 +9018,7 @@ void MainAbility::HybridCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9037,7 +9052,7 @@ void MainAbility::HybridCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList serialDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9064,7 +9079,7 @@ void MainAbility::HybridCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9091,12 +9106,12 @@ void MainAbility::HybridCase5(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::SYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) @@ -9137,12 +9152,12 @@ void MainAbility::HybridCase6(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) @@ -9183,12 +9198,12 @@ void MainAbility::HybridCase7(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; const long delay = 10; globalDispatcher.addOperation(TestOperation::DELAY) @@ -9236,12 +9251,12 @@ void MainAbility::HybridCase8(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9285,12 +9300,12 @@ void MainAbility::HybridCase9(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9334,12 +9349,12 @@ void MainAbility::HybridCase10(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; const long delay = 10; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) @@ -9387,12 +9402,12 @@ void MainAbility::HybridCase11(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9400,21 +9415,21 @@ void MainAbility::HybridCase11(int code) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9442,12 +9457,12 @@ void MainAbility::HybridCase12(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9502,12 +9517,12 @@ void MainAbility::HybridCase13(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 1; @@ -9559,12 +9574,12 @@ void MainAbility::HybridCase14(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9618,12 +9633,12 @@ void MainAbility::HybridCase15(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9635,7 +9650,7 @@ void MainAbility::HybridCase15(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::SYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9679,12 +9694,12 @@ void MainAbility::HybridCase16(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9707,7 +9722,7 @@ void MainAbility::HybridCase16(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9740,12 +9755,12 @@ void MainAbility::HybridCase17(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9795,12 +9810,12 @@ void MainAbility::HybridCase18(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9852,12 +9867,12 @@ void MainAbility::HybridCase19(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9910,12 +9925,12 @@ void MainAbility::HybridCase20(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9938,7 +9953,7 @@ void MainAbility::HybridCase20(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::DELAY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addDelay(delay) @@ -9971,12 +9986,12 @@ void MainAbility::HybridCase21(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9988,7 +10003,7 @@ void MainAbility::HybridCase21(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10031,12 +10046,12 @@ void MainAbility::HybridCase22(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10091,12 +10106,12 @@ void MainAbility::HybridCase23(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10120,7 +10135,7 @@ void MainAbility::HybridCase23(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::APPLY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10153,12 +10168,12 @@ void MainAbility::HybridCase24(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const long apply = 2; @@ -10169,8 +10184,8 @@ void MainAbility::HybridCase24(int code) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; - taskCount += 2; + taskId += numTwo; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::DELAY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addDelay(delay) @@ -10219,12 +10234,12 @@ void MainAbility::HybridCase25(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; globalDispatcher.addOperation(TestOperation::ASYNC) @@ -10245,7 +10260,7 @@ void MainAbility::HybridCase25(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10276,12 +10291,12 @@ void MainAbility::HybridCase26(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10332,12 +10347,12 @@ void MainAbility::HybridCase27(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10354,7 +10369,7 @@ void MainAbility::HybridCase27(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher2.addOperation(TestOperation::APPLY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addApply(apply) @@ -10395,7 +10410,7 @@ void MainAbility::MultiAppCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10427,7 +10442,7 @@ void MainAbility::MultiAppCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10459,7 +10474,7 @@ void MainAbility::MultiAppCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList serialDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10491,7 +10506,7 @@ void MainAbility::MultiAppCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10524,17 +10539,17 @@ void MainAbility::ExtraCase1(int code) Reset(); auto context = GetContext(); int taskId = 0; - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; bool result = globalDispatcher.addOperation(TestOperation::SYNC) - .addFunc(std::make_shared([=]() { - std::string targetBundleName = "com.ohos.TaskDispatcherA"; - std::string targetAbility = "SecondAbility"; - Want want; - want.SetElementName(targetBundleName, targetAbility); - StartAbility(want); - TestTask(std::to_string(taskId)); - })) - .executedTask(); + .addFunc(std::make_shared([=]() { + std::string targetBundleName = "com.ohos.TaskDispatcherA"; + std::string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundleName, targetAbility); + StartAbility(want); + TestTask(std::to_string(taskId)); + })) + .executedTask(); taskId++; Wait(taskId); result = task_execution_sequence.size() > 1; @@ -10547,7 +10562,7 @@ void MainAbility::FillInDispathcer() const int fullThreadNum = 32; const int waitTime = 2; auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; parallelDispatcher.setTaskPriority(AppExecFwk::TaskPriority::HIGH); parallelDispatcher.addOperation(TestOperation::ASYNC).addFunc(std::make_shared([=]() { sleep(waitTime - 1); @@ -10565,9 +10580,9 @@ void MainAbility::PriorityCase1(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList globalDispatcherLow = TaskList{TestDispatcher::GLOBAL, context, "globalLow"}; - TaskList globalDispatcherDefault = TaskList{TestDispatcher::GLOBAL, context, "globalDefault"}; - TaskList globalDispatcherHigh = TaskList{TestDispatcher::GLOBAL, context, "globalHigh"}; + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globalLow"}; + TaskList globalDispatcherDefault = TaskList {TestDispatcher::GLOBAL, context, "globalDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; int taskId = 0; globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10592,7 +10607,7 @@ void MainAbility::PriorityCase1(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase2(int code) @@ -10601,9 +10616,9 @@ void MainAbility::PriorityCase2(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcherLow = TaskList{TestDispatcher::PARALLEL, context, "parallelLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList parallelDispatcherHigh = TaskList{TestDispatcher::PARALLEL, context, "parallelHigh"}; + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList parallelDispatcherHigh = TaskList {TestDispatcher::PARALLEL, context, "parallelHigh"}; int taskId = 0; parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10628,7 +10643,7 @@ void MainAbility::PriorityCase2(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase3(int code) @@ -10637,9 +10652,9 @@ void MainAbility::PriorityCase3(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList serialDispatcherLow = TaskList{TestDispatcher::SERIAL, context, "serialLow"}; - TaskList serialDispatcherDefault = TaskList{TestDispatcher::SERIAL, context, "serialDefault"}; - TaskList serialDispatcherHigh = TaskList{TestDispatcher::SERIAL, context, "serialHigh"}; + TaskList serialDispatcherLow = TaskList {TestDispatcher::SERIAL, context, "serialLow"}; + TaskList serialDispatcherDefault = TaskList {TestDispatcher::SERIAL, context, "serialDefault"}; + TaskList serialDispatcherHigh = TaskList {TestDispatcher::SERIAL, context, "serialHigh"}; int taskId = 0; serialDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10664,7 +10679,7 @@ void MainAbility::PriorityCase3(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase4(int code) @@ -10673,9 +10688,9 @@ void MainAbility::PriorityCase4(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcherLow = TaskList{TestDispatcher::PARALLEL, context, "parallelLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList mainDispatcherHigh = TaskList{TestDispatcher::MAIN, context, "mainHigh"}; + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList mainDispatcherHigh = TaskList {TestDispatcher::MAIN, context, "mainHigh"}; int taskId = 0; parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10699,7 +10714,7 @@ void MainAbility::PriorityCase4(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase5(int code) @@ -10708,9 +10723,9 @@ void MainAbility::PriorityCase5(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList globalDispatcherLow = TaskList{TestDispatcher::GLOBAL, context, "globallLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList globalDispatcherHigh = TaskList{TestDispatcher::GLOBAL, context, "globalHigh"}; + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globallLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; int taskId = 0; globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10735,7 +10750,7 @@ void MainAbility::PriorityCase5(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::RevokeCase1(int code) @@ -10744,13 +10759,13 @@ void MainAbility::RevokeCase1(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10762,11 +10777,11 @@ void MainAbility::RevokeCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); @@ -10779,14 +10794,14 @@ void MainAbility::RevokeCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::DELAY) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addDelay(delayMs) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10798,12 +10813,12 @@ void MainAbility::RevokeCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::DELAY) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addDelay(delayMs) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); @@ -10817,14 +10832,14 @@ void MainAbility::RevokeCase5(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) - .addOperation(TestOperation::ASYNC_GROUP) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10836,12 +10851,12 @@ void MainAbility::RevokeCase6(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) - .addOperation(TestOperation::ASYNC_GROUP) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .executedTask(); + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp index 74b750fe7fa5a49e9051fd2107ca246fe119859a..57b1eff8c0d1ff2185e6f19582328e6236511c28 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp @@ -20,6 +20,14 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace +{ +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} // namespace + void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -109,11 +117,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) 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) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( 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()}; + 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/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/taskDispatcherTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h index e32f3c5521a3b852d7224e2e63db851c71226d23..f0ffaa195385b9f13d7fb5035a070d365485fe00 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - class TestUtils { public: TestUtils() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp index e80ab723aa4c01b840b256cef11908d2e0fa9606..5d6ca2081673da539f3284424e640e990472d4f8 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp @@ -25,7 +25,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::STtools; - +namespace { int terminated_task_num = 0; std::condition_variable cv; std::mutex cv_mutex; @@ -38,17 +38,28 @@ std::string outerSyncBarrierId = "outerSyncBarrierId"; std::string outerAsyncBarrierId = "outerAsyncBarrierId"; std::string outerGroupWaitId = "outerGroupWaitId"; std::string outerGroupNotifyId = "outerGroupNotifyId"; - std::string delimiter = "_"; std::string innerDelimiter = "-"; std::string task_execution_sequence = delimiter; +std::vector> allDispatchers; +std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} bool Wait(const int task_num) { APP_LOGI("-- -- -- -- -- --MainAbility::Wait"); std::unique_lock ulock(cv_mutex); using namespace std::chrono_literals; - return cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + bool result = cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + if (result) { + allDispatchers.clear(); + } + APP_LOGI("-- -- -- -- -- --MainAbility::Wait result:%{public}d", result); + return result; } void TestTask(const std::string &task_id) @@ -68,6 +79,7 @@ void Reset() APP_LOGI("-- -- -- -- -- --MainAbility::Reset"); terminated_task_num = 0; task_execution_sequence = delimiter; + allDispatchers.clear(); } bool IsAscend(const std::vector &vec) @@ -268,14 +280,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[0]=%{public}s", caseInfo[0].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[1]=%{public}s", caseInfo[1].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[2]=%{public}s", caseInfo[2].c_str()); - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -291,15 +300,92 @@ void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) } } +void SetInnerTask(TaskList innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) { + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} + +void SetInnerTaskOther(TaskList innerDispatcher, TestSetting innerSetting, int outerTaskSeq) { + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList outerDispatcher, TestSetting outerSetting) { + if (outerSetting.sync_barrier) { + auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (outerSetting.async_barrier) { + auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (outerSetting.group_wait) { + outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); + } + if (outerSetting.group_notify) { + auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); + outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) { + int taskCount = 0; + taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; + if (innerSetting.sync_barrier) { + taskCount++; + } + if (innerSetting.async_barrier) { + taskCount++; + } + if (innerSetting.group_notify) { + taskCount++; + } + taskCount = (outerSetting.op == TestOperation::APPLY) + ? (outerSetting.apply * testTaskCount + outerSetting.apply * testTaskCount * taskCount) + : (testTaskCount + testTaskCount * taskCount); + if (outerSetting.sync_barrier) { + taskCount++; + } + if (outerSetting.async_barrier) { + taskCount++; + } + if (outerSetting.group_notify) { + taskCount++; + } + return taskCount; +} + int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) { - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch begin"); std::string outerName = "outerDispatcher"; std::string innerName = "innerDispatcher"; - std::string outerTaskId; auto context = GetContext(); - TaskList outerDispatcher{outerSetting.dispatcher, context, outerName}; + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; if (outerSetting.create_group) { outerDispatcher.addOperation(TestOperation::CREATE_GROUP); } @@ -307,41 +393,19 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) outerTaskId = std::to_string(i); auto outerTask = std::make_shared([=]() { auto context = this->GetContext(); - TaskList innerDispatcher{innerSetting.dispatcher, context, innerName + std::to_string(i)}; + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; if (innerSetting.create_group) { innerDispatcher.addOperation(TestOperation::CREATE_GROUP); } for (int j = 0; j < testTaskCount; j++) { - std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(j); - auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); - innerDispatcher.addOperation(innerSetting.op); - if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { - innerDispatcher.addApply(innerSetting.apply); - } - if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { - innerDispatcher.addDelay(innerSetting.delay); - } - innerDispatcher.addFunc(innerTask); - } - if (innerSetting.sync_barrier) { - std::string taskId = innerSyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (innerSetting.async_barrier) { - std::string taskId = innerAsyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (innerSetting.group_wait) { - innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); - } - if (innerSetting.group_notify) { - std::string taskId = innerGroupNotifyId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); } + SetInnerTaskOther(innerDispatcher, innerSetting, i); innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } TestTask(outerTaskId); }); outerDispatcher.addOperation(outerSetting.op); @@ -353,29 +417,13 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) } outerDispatcher.addFunc(outerTask); } - if (outerSetting.sync_barrier) { - auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); - outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (outerSetting.async_barrier) { - auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); - outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (outerSetting.group_wait) { - outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); - } - if (outerSetting.group_notify) { - auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); - outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); - } + SetOuterTaskOther(outerDispatcher, outerSetting); outerDispatcher.executedTask(); - int taskCount = 0; - taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; - taskCount = (outerSetting.op == TestOperation::APPLY) - ? (innerSetting.apply * testTaskCount + innerSetting.apply * testTaskCount * taskCount) - : (testTaskCount + testTaskCount * taskCount); - - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch end"); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); return taskCount; } @@ -403,7 +451,7 @@ void MainAbility::MultiAppCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -435,7 +483,7 @@ void MainAbility::MultiAppCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList globalDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -467,7 +515,7 @@ void MainAbility::MultiAppCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList globalDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -499,7 +547,7 @@ void MainAbility::MultiAppCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp index 67a8ed8c7c7381c3e7297f5ad419e9dc0f3f95f3..9c770b1249159f651d0c48fcc98ac92003660c94 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -103,11 +109,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND_B.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( 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()}; + 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/tools/include/event.h b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h index 00ced741999b3e91b6f639acf99a7753263b6e04..4e659a7bd700b404d249954636828c6c3b3100d5 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/event.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h @@ -18,7 +18,6 @@ #include namespace STtools { - class Event { public: Event(); @@ -38,5 +37,4 @@ private: int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 60); void Completed(Event &event, const std::string &eventName, const int code); void CleanMsg(Event &event); - } // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h index c0683c1ae47c2b17ca607c8ff6a5448b7271722b..f7a8f367f01b3302b96144dfc2050e7bc2b07c21 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h @@ -20,11 +20,8 @@ namespace STtools { using std::string; class StOperator; - std::vector SerializationStOperatorToVector(StOperator &ParentOperator); - void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector &vectorOperator); - class StOperator { private: std::vector> g_childOperator; @@ -57,5 +54,4 @@ public: std::vector> GetChildOperator(); std::vector> PopChildOperator(); }; - } // namespace STtools diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h index aa2709a5d990518c2b8a93db06317479b693bef9..7c441e4f4dcf660e0f1f64ce5e8043175e17c3f7 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h @@ -22,12 +22,14 @@ #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 +42,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 +72,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 +93,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); @@ -107,8 +128,6 @@ private: std::string callBackPath_; std::string abilityStatus_; }; - } // namespace AppExecFwk } // namespace OHOS - -#endif //_AMS_ST_PAGE_ABILITY_EVENT_H_ \ No newline at end of file +#endif // _AMS_ST_PAGE_ABILITY_EVENT_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp index a51291b4b24bf14bfd45d1c6b27f4e390d2443e9..933a13149cedd0306a45973a8d488359257eb0c8 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp @@ -17,7 +17,6 @@ #include namespace STtools { - int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) { return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); @@ -98,5 +97,4 @@ void Event::Clean() waiting_message_ = ""; complete_message_.clear(); } - } // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp index 2c7ea20bc5fc7992fa9217e857611dfc0c303532..c441c6cedf8da2677a28bd6d63054022b3f9b581 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp @@ -75,7 +75,8 @@ void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector int StOperator::countChild = 0; StOperator::StOperator() - : g_parentOperator(nullptr), g_abilityType("0"), g_bundleName(""), g_abilityName(""), g_operatorName(""), g_message("") + : g_parentOperator(nullptr), g_abilityType("0"), + g_bundleName(""), g_abilityName(""), g_operatorName(""), g_message("") { g_childOperator.clear(); StOperator::countChild++; diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp index 3016490db6fd9bc38c6f2002ce545546c35b36e8..f13a7db485f029b3c0cf0c7a1b68f2d85d2bd663 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stpageabilityevent.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace AppExecFwk { - using namespace OHOS::EventFwk; STPageAbilityEvent::STPageAbilityEvent(const std::string &className) @@ -36,7 +35,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 +44,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 +136,57 @@ 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..e38e1d19b123368a02c279883e9ba92dca4bf356 --- /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_H +#define PAGE_ABILITY_DEMO_H +#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_H \ 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..b834cac390814cf09d24de1aa7bb36033bfe2a48 --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo1/src/pageAbilityDemo.cpp @@ -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. + */ +#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 +{ + + std::ofstream file(path); + file.close(); + + if (access(path.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", path.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..c430a0bf573938416747f8f0fac46975acd4d860 --- /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_H +#define PAGE_ABILITY_DEMO_H +#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_H \ 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..94f492c29d2ea5f96eb1cbe652d180bc3e03f5ac --- /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_H +#define PAGE_ABILITY_DEMO_H +#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_H \ 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..2ed39e4dc00aba02cd7e2f7b0b18483f6aecc0de --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.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 "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 +{ + + std::ofstream file(path); + file.close(); + + if (access(path.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", path.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..94f492c29d2ea5f96eb1cbe652d180bc3e03f5ac --- /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_H +#define PAGE_ABILITY_DEMO_H +#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_H \ 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..c38274be98c5d14ba657fd61e82a7e899a065f5b --- /dev/null +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo4/src/pageAbilityDemo.cpp @@ -0,0 +1,95 @@ +/* + * 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 +{ + + std::ofstream file(path); + file.close(); + + if (access(path.c_str(), F_OK) != 0) { + APP_LOGE("CreateFile-checkFile:%{public}s not exist", path.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..2f4694027cecda50600c937f94b5589c0681afd5 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..beb37783cd5602c6bf794e604d875e4915248e34 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..9b372a3eb69b2c3780d4b081faf757d097f3af9c 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..a8a9f62cab39664b7b0bc17910861266eef19a37 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/jsBundle/jsThirdBundle/bmsThirdBundleDataAbility.hap b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundleDataAbility.hap new file mode 100755 index 0000000000000000000000000000000000000000..21dc0f64c3386f5d9ce072dfa0c713313620992f Binary files /dev/null and b/test/resource/bundlemgrsst/jsBundle/jsThirdBundle/bmsThirdBundleDataAbility.hap differ diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle24.hap index f5cb92e3b8e3f0aae8502ea5477529d0e11b0a54..09cc073f733ed49b115a788edc902eca410e50c4 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..97fcb8e788eb23ceb06dcd960947b3253dfedbeb 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/bmsThirdBundle41.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap old mode 100755 new mode 100644 diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle44.hap new file mode 100644 index 0000000000000000000000000000000000000000..37a9ce79265e440f5bc98be1cb8ecb287b7e4a3c 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..c7748a8f14a7d264b1f626a959c303a0a26b1be3 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..eb3960bf94b35bb13afda611eb4587d6383ff8f3 --- /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_A.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..c7baafed52bb0c88b550f74f77a16c0b154ad98f --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/config.json @@ -0,0 +1,112 @@ +{ + "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": "moduleName11", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "FormStServiceAbilityA", + "icon": "$media:snowball", + "label": "FormStServiceAbilityA 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": "0:0", + "updateDuration": 1, + "deepLink": "", + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + }, + { + "name": "formName112", + "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": 0, + "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_A.h b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h new file mode 100755 index 0000000000000000000000000000000000000000..610caccc59c7c13bdcf5f2be0a3eabe5ea456860 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h @@ -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. + */ + +#ifndef FORM_ST_SERVICE_ABILITY_A_ +#define FORM_ST_SERVICE_ABILITY_A_ +#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_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_a"; +const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_a"; +const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; +/** + * Form event trigger result + */ +typedef enum { + FORM_EVENT_TRIGGER_RESULT_NG = 0, + FORM_EVENT_TRIGGER_RESULT_OK = 1, +} FORM_EVENT_TRIGGER_RESULT; + +class FormStServiceAbilityA : public Ability { +public: + ~FormStServiceAbilityA(); + +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 OnCreate(const Want &want) override; + virtual void OnUpdate(const int64_t formId) override; + virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; + virtual void OnDelete(const int64_t formId) override; + virtual void OnCastTemptoNormal(const int64_t formId) override; + virtual void OnVisibilityChanged(const std::map &formEventsMap) 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 (FormStServiceAbilityA::*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_A_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_A_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; + + FormStServiceAbilityA *mainAbility_ = nullptr; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FORM_ST_SERVICE_ABILITY_A_ 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 100755 index 0000000000000000000000000000000000000000..e5e30429343af0cdfe4aca95ac07ec9d7d07fd75 --- /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 OnCreate(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_A.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp new file mode 100755 index 0000000000000000000000000000000000000000..e229ca09f08fa93e2f8f9cd9d08d5ca851d76f52 --- /dev/null +++ b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.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 "form_st_service_ability_A.h" +#include "app_log_wrapper.h" +#include "common_event.h" +#include "common_event_manager.h" +#include "form_provider_client.h" + +using namespace OHOS::EventFwk; + +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; + +namespace OHOS { +namespace AppExecFwk { +using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; + +int FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +std::map FormStServiceAbilityA::funcMap_ = { + {"StartOtherAbility", &FormStServiceAbilityA::StartOtherAbility}, + {"ConnectOtherAbility", &FormStServiceAbilityA::ConnectOtherAbility}, + {"DisConnectOtherAbility", &FormStServiceAbilityA::DisConnectOtherAbility}, + {"StopSelfAbility", &FormStServiceAbilityA::StopSelfAbility}, +}; + +FormStServiceAbilityA::~FormStServiceAbilityA() +{ + CommonEventManager::UnSubscribeCommonEvent(subscriber_); +} + +std::vector FormStServiceAbilityA::Split(std::string str, const std::string &token) +{ + APP_LOGI("FormStServiceAbilityA::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 FormStServiceAbilityA::StartOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", + targetBundle_.c_str(), + targetAbility_.c_str()); + APP_LOGI("FormStServiceAbilityA::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 FormStServiceAbilityA::ConnectOtherAbility() +{ + APP_LOGI( + "FormStServiceAbilityA::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", + targetBundleConn_.c_str(), + targetAbilityConn_.c_str()); + APP_LOGI("FormStServiceAbilityA::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("FormStServiceAbilityA::ConnectOtherAbility->ConnectAbility"); + bool ret = ConnectAbility(want, connCallback_); + sleep(1); + if (!ret) { + APP_LOGE("FormStServiceAbilityA::ConnectAbility failed!"); + } + } + } +} +void FormStServiceAbilityA::DisConnectOtherAbility() +{ + APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility begin"); + if (connCallback_ != nullptr) { + DisconnectAbility(connCallback_); + sleep(1); + } + APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility end"); +} + +void FormStServiceAbilityA::StopSelfAbility() +{ + APP_LOGI("FormStServiceAbilityA::StopSelfAbility"); + + TerminateAbility(); +} + +void FormStServiceAbilityA::OnStart(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnStart"); + + GetWantInfo(want); + Ability::OnStart(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); + SubscribeEvent(); + + // make exception for test + if (!zombie_.empty()) { + std::unique_ptr pWant = nullptr; + pWant->GetScheme(); + } +} +void FormStServiceAbilityA::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + APP_LOGI("FormStServiceAbilityA::OnCommand"); + + GetWantInfo(want); + Ability::OnCommand(want, restart, startId); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); +} +void FormStServiceAbilityA::OnNewWant(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnNewWant"); + + GetWantInfo(want); + Ability::OnNewWant(want); +} +void FormStServiceAbilityA::OnStop() +{ + APP_LOGI("FormStServiceAbilityA::OnStop"); + + Ability::OnStop(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); +} +void FormStServiceAbilityA::OnActive() +{ + APP_LOGI("FormStServiceAbilityA::OnActive"); + + Ability::OnActive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); +} +void FormStServiceAbilityA::OnInactive() +{ + APP_LOGI("FormStServiceAbilityA::OnInactive"); + + Ability::OnInactive(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); +} +void FormStServiceAbilityA::OnBackground() +{ + APP_LOGI("FormStServiceAbilityA::OnBackground"); + + Ability::OnBackground(); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); +} + +void FormStServiceAbilityA::Clear() +{ + shouldReturn_ = ""; + targetBundle_ = ""; + targetAbility_ = ""; + targetBundleConn_ = ""; + targetAbilityConn_ = ""; + nextTargetBundle_ = ""; + nextTargetAbility_ = ""; + nextTargetBundleConn_ = ""; + nextTargetAbilityConn_ = ""; +} +void FormStServiceAbilityA::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"); + FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; +} +bool FormStServiceAbilityA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) +{ + APP_LOGI("FormStServiceAbilityA::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 FormStServiceAbilityA::OnConnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnConnect"); + + sptr formProviderClient = new (std::nothrow) FormProviderClient(); + std::shared_ptr thisAbility = this->shared_from_this(); + formProviderClient->SetOwner(thisAbility); + + return formProviderClient; +} +void FormStServiceAbilityA::OnDisconnect(const Want &want) +{ + APP_LOGI("FormStServiceAbilityA::OnDisconnect"); + + Ability::OnDisconnect(want); + PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); +} +bool FormStServiceAbilityA::SubscribeEvent() +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); + CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetPriority(1); + subscriber_ = std::make_shared(subscribeInfo); + subscriber_->mainAbility_ = this; + return CommonEventManager::SubscribeCommonEvent(subscriber_); +} +void FormStServiceAbilityA::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + auto eventName = data.GetWant().GetAction(); + auto dataContent = data.GetData(); + APP_LOGI("FormStServiceAbilityA::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", + eventName.c_str(), + data.GetCode(), + dataContent.c_str()); + if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { + if (funcMap_.find(dataContent) == funcMap_.end()) { + APP_LOGI( + "FormStServiceAbilityA::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 FormStServiceAbilityA::OnCreate(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); + std::string jsonData = std::string("{\"city\":\"beijingA\"}"); + FormProviderData formProviderData = FormProviderData(jsonData); + formProviderInfo.SetFormData(formProviderData); + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCreate"); + APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); + return formProviderInfo; +} + +void FormStServiceAbilityA::OnUpdate(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); + APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); +} + +void FormStServiceAbilityA::OnTriggerEvent(const int64_t formId, const std::string &message) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); + APP_LOGI("%{public}s end, formId: %{public}lld, message: %{public}s, current time: %{public}ld", __func__, formId, message.c_str(), currentTime); +} + +void FormStServiceAbilityA::OnDelete(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnDelete"); + APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); +} + +void FormStServiceAbilityA::OnCastTemptoNormal(const int64_t formId) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCastTemptoNormal"); + APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); +} + +void FormStServiceAbilityA::OnVisibilityChanged(const std::map &formEventsMap) +{ + APP_LOGI("%{public}s start", __func__); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; + + PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnVisibilityChanged"); + APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); +} + +REGISTER_AA(FormStServiceAbilityA); +} // namespace AppExecFwk +} // namespace OHOS 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 100755 index 0000000000000000000000000000000000000000..8a3d6e97ff72f23d2984f4ebc23169c90fef389e --- /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::OnCreate(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/resource/tools/ohos_test.xml b/test/resource/tools/ohos_test.xml index f9d16b228f692ae53b0ee19d0aed33f704929335..150b04469921247d4139b76c186d40d9bf690417 100644 --- a/test/resource/tools/ohos_test.xml +++ b/test/resource/tools/ohos_test.xml @@ -14,19 +14,19 @@ * limitations under the License. --> - + - + - +